Angular 4 – 如何访问模板中的嵌套组件?

前端之家收集整理的这篇文章主要介绍了Angular 4 – 如何访问模板中的嵌套组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个组件层次结构:

App
|
Child
|
Input

组件“Child”接受来自其父级的模板,如下所示:

<my-child>
    <ng-template>
        <my-input></my-input>
        <span>asdasdas</span>
        <my-input></my-input>
        <my-input></my-input>
    </ng-template>    
</my-child>

正如您在模板中看到的那样,有许多输入组件.现在我想访问< my-input>列表.子组件中的组件.我现在尝试的是使用@ ContentChildren / @ ViewChildren,但它似乎不起作用.子组件的代码

@Component({
  selector: 'my-child',providers: [],template: `
    <div>
      <ng-template [ngTemplateOutlet]="inputTemplate" #input></ng-template>
    </div>
  `,directives: []
})

export class Child implements OnInit,OnAfterViewInit {

  @ContentChild(TemplateRef) inputTemplate: TemplateRef<any>;

  @ViewChildren(InputComponent) inputComponents : QueryList<InputComponent>;

  constructor() {

  }

  ngAfterViewInit(){
    //THIS SHOULD NOT BE EMPTY
    console.log(this.inputComponents.toArray());
  }
}

请让我知道我做错了什么,以及如何从Child组件中获取InputComponents列表.

也许我不应该在这里使用模板?有没有其他方法可以自定义此控件,仍然可以访问嵌套的InputComponents列表?

如果你想玩它here’s the plunker

解决方法

使用@ContentChildren(InputComponent)代替@ViewChildren()并订阅更改

ngAfterViewInit(){
    //THIS SHOULD NOT BE EMPTY
    this.inputComponents.changes.subscribe(c => console.log(this.inputComponents.toArray()));
    //console.log(this.inputComponents.toArray());
  }

为我工作,但说实话,我不知道自己为什么@ContentChildren()而不是@ViewChildren()正在工作.

Plunker link

猜你在找的Angularjs相关文章