Angular:是否可以从特定组件查询所有DOM的元素?

问题描述

具有以下DOM代码段:

<ng-app>
  <ng-comp1></ng-comp1>
  <ng-comp2>
     <ng-comp3></ng-comp3>
  </ng-comp2>
  <ng-comp1></ng-comp1>
</ng-app>

我想从ng-comp3列出DOM文档中的所有组件ng-comp1。有办法吗?

ViewChildren仅列出ng-comp3内部的组件。

document.querySelector列出DOM元素,而不是组件。

解决方法

简短的回答是“不,您不能直接列出它们”。

另一方面,您可以将ng-app注入您的ng-comp3组件中,并通过ng-comp1ng-app进行交互。

I have put an example here

@Component({
  selector: 'inner-hello',template: `<h1>Hello {{name}}!</h1>`,styles: [`h1 { font-family: Lato; }`]
})
export class InnerHelloComponent implements AfterViewInit  {
  @Input() name: string;

  constructor(@Inject(forwardRef(() => AppComponent)) private app: AppComponent) {
    console.log(app.name);
  }

  ngAfterViewInit() {
    // Here you will be able to access your ViewChild
  }
}

别忘了ViewChild被解雇之前,ViewChildrenngAfterViewInit不会被填充

可能已经注意到,这个想法是在ng-comp1组件中查询ng-app,将其存储在公共变量中,然后从ng-comp3访问它。在我的示例中,以相同的方式访问属性name