【问题标题】:How to get works ViewChildren with NgTemplateOutlet? (4.0.0-rc1)如何使用 NgTemplateOutlet 获取作品 ViewChildren? (4.0.0-rc1)
【发布时间】:2017-03-01 10:54:13
【问题描述】:

我想用 NgTemplateOutlet 创建孩子。

我有这个example plunkr,我有子组件和父组件,父组件有一个使用 ngTemplateOutlet 呈现的输入模板:

@Component({
  selector: 'parent',
  template: `
    <div>parent</div>
    <ng-container *ngTemplateOutlet="template1"></ng-container>
    <div *ngFor="let child of children; let i = index">{{i}}</div>
    {{children.length}}    
`
})
export class Parent {
  @Input() template1; 
  children = [];
  @ViewChildren(Child) viewList: QueryList<Child>;

  updateElements() {
    setTimeout(() => this.children = this.viewList.toArray());
  }

  ngAfterViewInit() {
    this.viewList.changes.subscribe(() => this.updateElements());
    this.updateElements();
  }      
}

父组件尝试使用ViewChildren 获取Child 子组件,但不起作用。

有人知道怎么弄吗?

另一方面,我写了other plunkr,我在其中使用 ngFor 来渲染几个子组件并且它可以工作。

由于 ngFor 和 ngTemplateOutlet 都使用viewContainerRef.createEmbeddedView,我认为两种方法应该以相同的方式工作。

为什么不呢?

PS:我使用的是 Angular 4.0.0-rc1,但我认为 Angular 2.x 也是如此

【问题讨论】:

    标签: angular


    【解决方案1】:

    与此同时,您可以使用解决方法将父级注入子级。

    【讨论】:

    • 直到我明白,appcomponent 上的子组件从父组件获取注入器......然后他们收到了 appcomponent 注入器,然后 Angular 无法注入父组件。
    • 其实不是很明显,问题是createEmbeddedView没有把injector作为参数,这就引出了另一个问题,为什么模板父injector是继承自定义模板的组件?对我来说看起来像是限制/错误,它应该是可配置的。我认为它解释了为什么ViewChildren/ContentChildren 不起作用。
    • 操作,我只是想看看你的问题。好的,如果您有任何回应,请告诉我。
    • @kemsky 进一步的解释可能非常有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2019-05-01
    相关资源
    最近更新 更多