angular 组件能否从 ist outer/parent 组件获取数据

Can a angular component get data from ist outer/parent component

我制作了 angular 个组件并将它们用作 HTML 中的元素。喜欢:

<my-parent [setting]="A">
    <my-child-1>...</my-child-1>
    <my-child-2>...</my-child-2>
</my-parent>
<my-parent [setting]="B">
    <my-child-1>...</my-child-1>
    <my-child-2>...</my-child-2>
</my-parent>

所以 MyParent 组件有一个 @Input() 属性 被赋予了一些设置。 但是它的 children 也需要得到这个设置。而且我宁愿不必将 [setting]="A" 添加到所有 children (因为实际上它不仅仅是一个参数)。 有没有办法让 child 组件从它的 parent 中得到这个 属性? 注意可以有多个parents,所以如果我使用服务作为通信平台,children需要有一些parent的id,以避免从错误的parent。但我宁愿不必将此 ID 传递给所有 children.

如果您的 children 始终是 parent,您可以使用 @Host

在构造函数中注入 parent
   constructor(@Optional() @Host() private parent: ParentComponent){}

所以你可以在任何地方使用

  //see that always check if parent is not null or undefined
  if (this.parent)
  {
      console.log(this.parent.setting)
  }

例如你可以有一个 getter

   get settingParent()
   {
        //see that always check if parent is not null or undefined
        return this.parent?this.parent.setting:null;
   }