【问题标题】:Angular 2 - Access child component property generated from router-outletAngular 2 - 访问从路由器出口生成的子组件属性
【发布时间】: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和使用&lt;router-outlet&gt;&lt;/router-outlet&gt;动态生成子组件,我得到的结果是未定义的。

你知道如何做到这一点吗?

【问题讨论】:

标签: angular


【解决方案1】:

如果您的目标只是从您的孩子那里访问一个值/方法,您可以简单地使用 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);
        }
     }

【讨论】:

  • 这不是static的用法