[英]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-app
與ng-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
}
}
不要忘記ViewChild
和ViewChildren
在ngAfterViewInit
被觸發之前不會被填充
可能已經注意到,這個想法是在ng-app
組件中查詢ng-comp1
,將其存儲在公共變量中並從ng-comp3
訪問它。 與我在示例中訪問屬性name
方式相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.