如何从父组件获取自定义组件的子组件

fat*_*tah 3 angular2-directives angular2-template angular

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

@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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

vin*_*nce 6

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

class CustomComponent {
  @ViewChildren(ChildComponent) myChildren: QueryList<ChildComponent>;
}
Run Code Online (Sandbox Code Playgroud)

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

class ParentComponent {
  @ViewChild(CustomComponent) customComp: CustomComponent;
}
Run Code Online (Sandbox Code Playgroud)

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

ngAfterViewInit() {
  const grandchildren = this.customComp.myChildren;
}
Run Code Online (Sandbox Code Playgroud)

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

一些注意事项:

  • 不要尝试访问您的@ViewChildUntilAfterViewInit生命周期挂钩。看到@DeborahK的评论后,我觉得我应该更多地强调这一点,所以我把它加粗了。这可能是您当前代码的唯一问题。
  • 将您的属性键入@ViewChild为组件本身 ( CustomComponent),而不是ElementRef.