angular的ng-content实践总结

2020-04-29  本文已影响0人  草珊瑚_6557

父组件获取子组件的实例

项目中使用父组件套子组件的代码(非父组件的模板代码)

<father>
  <son #sonComponetInstance></son>
</father>

父组件的ts代码

export class fatherComponent implements OnInit {
  @ContentChild('sonComponetInstance') son:any;

  ngAfterContentInit(){
    console.log('ngAfterContentInit',this.son);
  }
}

子组件使用父组件的能力

import { Component, OnInit, Host, Input } from '@angular/core';
import {fatherComponent} from '../fatherComponent.component';


export class ChildInputComponent implements OnInit {

  keyword:string;

  constructor(
    @Host() private parent: InputAutocompleteComponent
  ) { }
  onSearch(){
    // 使用父组件的能力
    this.parent.onSearch.call(this.parent, this.keyword);
  }
}
上一篇下一篇

猜你喜欢

热点阅读