【问题标题】:How to get the name of the Parent component in Child component in angular 2?如何在 Angular 2 中获取子组件中父组件的名称?
【发布时间】:2018-05-21 18:41:19
【问题描述】:

假设我有三个组件:C1、C2 和 C3。

我想让 C2 成为 C1 和 C3 的孩子。 并且根据哪个组件是 C2 的父级的事实想要显示 HTML 文本 - “C1 是我的父级”或“c3 是我的父级”。 这是我的问题的表面形式。 我想在c2中访问父组件的名字,然后相应地改变它的innerHTML。

angular2中如何访问父组件的名称?

【问题讨论】:

    标签: angular parent-child mean-stack


    【解决方案1】:

    您可以通过 @Input 简单地将描述您的父组件的内容传递给子组件。

    子组件示例:

    @Component({
      selector: 'child',
      template: `
        <div>{{ parentName }} is my parent</div>
      `,
    })
    export class ChildComponent {
      @Input() parentName: string;
    }
    

    第一个父母:

    @Component({
      selector: 'first-parent',
      template: `
        <child-component parentName="'first-parent-component'" />
      `,
    })
    export class FirstParentComponent {
    }
    

    第二个父母:

    @Component({
      selector: 'second-parent',
      template: `
        <child-component parentName="'second-parent-component'" />
      `,
    })
    export class SecondParentComponent {
    }
    

    【讨论】:

    • 是的,我正在使用它,但我认为必须有其他特定的方式来完成这项工作,我们可以直接获取父组件的名称。
    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多