我正在嘗試從父級呼叫子組件的視圖子級并在控制臺中未定義。
看圖片也可以看到相同的
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);
}
}
請幫助獲取子組件
this.testChildComponent
這樣我就可以從父母那里呼叫孩子的 ngOnInit。
this.testChildComponent.ngOnInit()
uj5u.com熱心網友回復:
ViewChild 元素 ref 最早可以ngAfterViewInit()回圈訪問。

Angular 檔案說我們應該在 ngAfterViewInit 中使用 ViewChild 注入的子組件。但有時你甚至無法在 ngAfterViewInit 中得到它。原因是,在 AfterViewInit 鉤子運行時,子組件尚未創建。對于這種情況,您將不得不等待更多時間(使用 asetTimeout會起作用,但這是一個壞主意)。其他選擇是讓孩子向父母發出一些東西,讓它知道孩子已經被渲染,然后父母可以查詢它。
但是你的情況是兄弟HelloComponent想查詢兄弟TestChildComponent它不能這樣做。TestChildComponent只是不在范圍內HelloComponent。最簡單的解決方案是TestChildComponent從 parent查詢AppComponent。
您還應該添加#TestChildComponent以訪問參考。
<app-test-child #TestChildComponent childname="{{ name }}"></app-test-child>
作業示例:https ://stackblitz.com/edit/angular-ivy-j5ceat???file=src/app/app.component.html
uj5u.com熱心網友回復:
如果您設定 viewChild { static: true } 您將能夠在 ngOnInit 中訪問它
但在您的示例中,問題是由于 testChildComponent 是 app.component 而不是 hello.component 的孩子
<app-test-child childname="{{ name }}" #test></app-test-child>
app.component.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/app/app.component.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452436.html
標籤:javascript html 有角度的 打字稿 角13
上一篇:無法系結到“禁用”,因為它不是“應用按鈕”的已知屬性
下一篇:如何使用字串設定材質圖示?
