【问题标题】:How to get children of custom component from parent如何从父级获取自定义组件的子级
【发布时间】:2018-01-31 19:53:31
【问题描述】:

我正在尝试使用以下代码获取自定义书面组件的子代:

@Component({
  selector: 'custom-comp',
  templateUrl: '<div class='child1'></div><div class='child2'></div>',
  styleUrls: ['./custom-comp.component.scss']
})
@Component({
      selector: 'comp',
      templateUrl: '<#custom-comp custom-comp></custom-comp>',
      styleUrls: ['./custom-comp.component.scss']
    })

@ViewChild('custom-comp') custom-comp: ElementRef;
ngOnInit(){
    console.log(this.custom-comp.nativeElement.children);
}

它返回此错误: 无法读取未定义的属性“孩子”

结论是这种方法仅适用于原生 HTML 元素,我如何为自定义组件做到这一点?谢谢 !

【问题讨论】:

  • 您需要将日志从ngOnInit 移动到ngAfterViewInitViewChild 修饰的属性在视图初始化之前是不可靠的。

标签: angular angular2-template angular2-directives


【解决方案1】:

我不会使用nativeElement.children,而是在自定义组件中使用@ViewChildren 装饰器来使子组件在CustomComponent 的属性中可用,我们称之为myChildren,如下所示:

class CustomComponent {
  @ViewChildren(ChildComponent) myChildren: QueryList<ChildComponent>;
}

然后使用@ViewChild 装饰器来获取实际的组件,而不仅仅是ElementRef

class ParentComponent {
  @ViewChild(CustomComponent) customComp: CustomComponent;
}

然后像这样访问自定义组件上的myChildren 属性:

ngAfterViewInit() {
  const grandchildren = this.customComp.myChildren;
}

这个答案做了一个简化的假设,即您知道您想要获得的大孩子的类型,并且您不只是试图获得自定义组件的“所有”孩子。

几点说明:

  • AfterViewInit 生命周期钩子之前不要尝试访问您的@ViewChild 看到@DeborahK 的评论后,我觉得我应该更多地强调这一点,所以我用粗体表示。 这可能是您当前代码的唯一问题。
  • 键入您的 @ViewChild 属性作为组件本身 (CustomComponent),而不是 ElementRef

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多