无法到达父组件中的@ViewChildren [英] Can't get to @ViewChildren in parent component

查看:151
本文介绍了无法到达父组件中的@ViewChildren的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试控制组件的子代实例,并且不能越过错误.我正在尝试遵循

I am trying to get control over the children instances of a component and can't go past an error. I am trying to follow along the answers from this issue.

父组件Sequence包含SequenceStep的子组件.父级包含以下声明:

The parent component Sequence contains children components of SequenceStep. The parent contains the following declaration:

@ViewChildren(SequenceStep) steps: QueryList<SequenceStep>;

然后我要对孩子们做些事情:

then I am trying to do something about the children:

ngAfterViewInit() {
    this.steps.changes.subscribe(steps => {
        console.log(steps);
    });
}

我得到的错误是:

metadata_resolver.js:639未捕获的错误:无法构造查询 由于查询选择器不是序列"的属性步骤" 定义.

metadata_resolver.js:639 Uncaught Error: Can't construct a query for the property "steps" of "Sequence" since the query selector wasn't defined.

SequenceSequenceStep组件的确在其@Component装饰器中分别定义了选择器(分别为sequencesequence-step).

whereas both Sequence and SequenceStep components do have their selectors defined in their @Component decorators (sequence and sequence-step respectively).

我在做什么错了?

推荐答案

有几件事

  • 如果您从外面传递孩子,他们就是孩子而不是孩子. @ViewChild()仅适用于直接添加到组件模板的子代.

  • If you pass children from the outside, they are content not children. @ViewChild() only works for children added to the template of a component directly.

@ContentChildren()适用于被包含的内容:

@ContentChildren() works on transcluded content:

@ContentChildren(TheChild) kids: QueryList<TheChild>;

  • this.kids.changes()仅在初始化后通知更改. 因此,只需直接在ngAfterViewInit()中访问this.kids,然后订阅即可获得有关以后的更改的通知

  • this.kids.changes() only notifies about changes after the initialization. Therefore just access this.kids directly in ngAfterViewInit() and then subsribe to get notified about later changes

    ngAfterViewInit() {
      this.myKidsCount = this.kids.length;
      this.cdRef.detectChanges();
    
      this.kids.changes.subscribe(kids => {
          this.myKidsCount = kids.length;
      });
    }
    

  • 当更改检测导致更改时,Angular不喜欢. ngAfterViewInit()被更改检测调用,这就是this.myKidsCount = this.kids.length导致异常的原因.

  • Angular doesn't like when change detection causes changes. ngAfterViewInit() is called by change detection, this is why this.myKidsCount = this.kids.length causes an exception.

    要变通,我在更改属性myKidsCount后明确调用了更改检测:

    To work around I invoke change detection explicitly after changing the property myKidsCount:

    constructor(private cdRef:ChangeDetectorRef){}
    
    ngAfterViewInit() {
      this.myKidsCount = this.kids.length;
      this.cdRef.detectChanges();
    }
    

    柱塞示例

    这篇关于无法到达父组件中的@ViewChildren的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆