Angular @ViewChild @ViewChildren @ContentChild @ContentChildren 之间的区别

Angular @ViewChild @ViewChildren @ContentChild @ContentChildren 之间的区别

1.何时使用ViewChild和ViewChildren
当在写一个组件时,如果明确template中把其他组件放置上去,这个时候就可以使用@ViewChild(XXXComponent) componet:Componet 或者 @ViewChildren(XXComponent) components:QueryList;
2.何时使用ContentChild和ContentChildren
如果是隐式的使用其他组件,比如说这个组件将作为模板放到当前组件。或者说这个组件将会被投影到当前组件,则需要用到@ContentChild(XXXComponent) componet:Componet和@ContentChildren(XXComponent) components:QueryList;
示例

export class PanelContent{
  constructor(public templateRef: TemplateRef<any>){
  }
}
@Component({
  selector: 'panel',
  template: `
    <panel-info></panel-info>
    <ng-content select="content"></ng-content>
    <ng-template [ngTemplateOutlet]="panelContent.templateRef"></ng-template>
  `
})
export class Panel implements AfterViewInit{

  message="message";
  @ViewChild(PanelInfo) panelInfo:PanelInfo;

  @ContentChild(PanelTitle) panelTitle:PanelTitle;
  @ContentChild(PanelContent) panelContent: PanelContent;
  ngAfterViewInit() {
    console.log(this.panelInfo.info);
    console.log(this.panelTitle.title);
  }
}

猜你喜欢

转载自blog.csdn.net/qq_35501580/article/details/81509840