【发布时间】:2025-12-19 12:55:11
【问题描述】:
通常,我可以使用 @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>动态生成子组件,我得到的结果是未定义的。
你知道如何做到这一点吗?
【问题讨论】:
-
不支持与路由器添加的组件绑定。您可以改用共享服务。 angular.io/docs/ts/latest/cookbook/component-communication.html
标签: angular