【问题标题】:Can't get to @ViewChildren in parent component无法访问父组件中的@ViewChildren
【发布时间】:2016-10-10 12:21:56
【问题描述】:

我正在尝试控制组件的子实例,并且无法越过错误。我正在尝试遵循this issue 的答案。

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

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

那我想对孩子们做点什么:

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

我得到的错误是:

metadata_resolver.js:639 未捕获错误:无法构造查询 “序列”的属性“步骤”,因为查询选择器不是 已定义。

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

我在这里做错了什么?

【问题讨论】:

  • 你能在 plunker 中复制吗?
  • @GünterZöchbauer 抱歉,我花了一段时间才重新创建 plnkr,但这里是:plnkr.co/edit/tusSBpbmyoG6TQTcV2i0?p=preview 它不工作(请查看控制台) - 问题是:代码是否正确?

标签: angular typescript angular-decorator


【解决方案1】:

您是否尝试在 @ViewChildren 参数中添加引号?

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

【讨论】:

  • 引号仅用于查询模板变量名称,在查询组件或指令类型时,不得使用引号。
【解决方案2】:

此问题可能与SequenceStep的导入有关,请检查相关导入行的类名。

【讨论】:

  • 同意。此外,如果您有一个与父组件在同一文件中定义的指令(ViewChild),则必须先定义指令。
【解决方案3】:

有几件事

  • 如果你从外面传递孩子,他们是满足而不是孩子。 @ViewChild() 仅适用于直接添加到组件模板中的子组件。

    @ContentChildren() 处理嵌入内容:

    @ContentChildren(TheChild) kids: QueryList<TheChild>;
    
  • this.kids.changes() 仅在初始化后通知更改。 因此,只需直接在ngAfterViewInit() 中访问this.kids,然后订阅以获取有关后续更改的通知

    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 导致异常的原因。

为了解决这个问题,我在更改属性 myKidsCount 后显式调用更改检测:

constructor(private cdRef:ChangeDetectorRef){}

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

Plunker example

【讨论】:

    【解决方案4】:

    @ViewChildren('SequenceStep') steps: QueryList&lt;SequenceStep&gt;;

    为我工作。 Angular 4.X.X Angular CLI 1.X.X

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 2020-06-17
      • 2019-06-29
      • 1970-01-01
      • 2020-12-31
      • 2021-08-01
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多