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);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值