簡體   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