如何在angular 2的子组件中获取父组件的名称?

Ash*_*rma 11 parent-child mean-stack angular

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

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

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

Pat*_*łaś 6

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

子组件示例:

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

第一位家长:

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

第二位家长:

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

  • 是的,我正在使用它,但我认为必须有其他特定的方式来完成这项工作,我们可以通过它直接获取父组件的名称。 (2认同)