繁体   English   中英

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

[英]Angular: possible to queries elements of all DOM from a specific component?

使用下面的 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-appng-comp1交互。

我在这里放了一个例子

@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
  }
}

不要忘记ViewChildViewChildrenngAfterViewInit被触发之前不会被填充

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM