通常,我可以使用@ViewChild轻松地从父组件访问子组件属性。
App.component.ts (父组件)
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-app',
template: '<h1>My First Angular App</h1> <child-app></child-app>'
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent
ngAfterViewInit() {
console.log("This is app component ");
console.log(this.childComponent.name);
}
}
child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-app',
template: '<h2>This is my child</h2>'
})
export class ChildComponent {
// some attribute
name: any = "Kid";
callChild(): void{
console.log("Hello, I am your son");
}
}
如果子组件指令直接嵌套在父组件中,则很容易。但是,在父组件中,如果我通过配置route
并使用<router-outlet></router-outlet>
动态生成子项,则我将结果视为未定义。
你知道如何实现这个目标吗?
答案 0 :(得分:0)
如果您的目标只是从您的孩子访问值/方法,您只需使用static关键字即可。请参阅下面的代码更改
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-app',
template: '<h1>My First Angular App</h1> <child-app></child-app>'
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent
ngAfterViewInit() {
ChildComponent.callChild("PArent");
}
}
child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-app',
template: '<h2>This is my child</h2>'
})
export class ChildComponent {
// some attribute
name: any = "Kid";
static callChild(txt:string): void{
console.log("Inside child - Hello, from: " + txt);
}
}