[英]ViewChild is undefined in angular 13
我正在嘗試從父組件調用子組件的視圖子組件,並在控制台中獲取 undefined 。
看到圖像也看到相同的堆棧火焰
https://stackblitz.com/edit/angular-ivy-k4m2hp?file=src%2Fapp%2Fhello.component.ts
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';
@Component({
selector: 'hello',
template: `<h1>this is Hello component {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
@Input() name: string;
@ViewChild('TestChildComponent') testChildComponent: TestChildComponent
ngOnInit() {
console.log('calling ngOninit in hello component');
console.log('going to call test child instance this.TestChildComponent.ngOninit')
console.log(this.testChildComponent);
}
}
請幫助獲取子組件
這個.testChildComponent
這樣我就可以從父母那里打電話給孩子的 ngOnInit 。
this.testChildComponent.ngOnInit()
最早可以在ngAfterViewInit()
循環中訪問 ViewChild 元素 ref。
Angular 文檔說我們應該在 ngAfterViewInit 中使用 ViewChild 注入的子組件。 但有時你甚至無法在 ngAfterViewInit 中獲取它。 原因是 AfterViewInit 鈎子運行時子組件尚未創建。 對於這種情況,您將不得不等待更多時間(使用setTimeout
會起作用,但這是個壞主意)。 另一種選擇是讓孩子向父母發出一些東西,讓它知道孩子已經被渲染,然后父母可以查詢它。
但是你的情況是兄弟HelloComponent
想要查詢兄弟TestChildComponent
它不能這樣做。 TestChildComponent
不在HelloComponent
的 scope 中。 最簡單的解決方案是從父AppComponent
TestChildComponent
您還應該添加#TestChildComponent
以訪問 ref。
<app-test-child #TestChildComponent childname="{{ name }}"></app-test-child>
工作示例: https://stackblitz.com/edit/angular-ivy-j5ceat?file=src%2Fapp%2Fapp.component.html
如果你設置你的 viewChild { static: true } 你將能夠在 ngOnInit 中訪問它
但在您的示例中,問題是由於 testChildComponent 是 app.component 而不是 hello.component 的子項
<app-test-child childname="{{ name }}" #test></app-test-child>
應用程序組件.ts
import { Component, VERSION, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'this is from app compoenent';
@ViewChild('test', { static: true }) testChildComponent: TestChildComponent;
ngOnInit() {
console.log('calling ngOninit in app component');
console.log(this.testChildComponent);
}
}
如果你想從 hello.component 訪問 testChildComponent ,你必須將組件作為示例的輸入發送給它
遵循訪問 testChildComponent 的工作示例
https://stackblitz.com/edit/angular-ivy-tvwukg?file=src%2Fapp%2Fapp.component.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.