Sma*_*EGA 5 html javascript typescript angular angular13
我试图从父组件调用子组件的视图子组件,但在控制台中未定义。
查看图像还可以看到相同的堆栈火焰
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);
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙获取子组件
this.testChildComponent
这样我就可以从父级调用子级的 ngOnInit 。
this.testChildComponent.ngOnInit()
如果你设置 viewChild { static: true } 你将能够在 ngOnInit 中访问它
但在您的示例中,问题是由于 testChildComponent 是 app.component 而不是 hello.component 的子级
<app-test-child childname="{{ name }}" #test></app-test-child>
Run Code Online (Sandbox Code Playgroud)
应用程序组件.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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想从 hello.component 访问 testChildComponent,您必须将组件作为示例的输入发送给它
以下是访问 testChildComponent 的工作示例
https://stackblitz.com/edit/angular-ivy-tvwukg?file=src%2Fapp%2Fapp.component.html