发送父级对子级组件的引用

时间:2019-04-11 21:27:22

标签: angular

我想发送父级对子级组件的引用,希望带有以下内容:

<parent-component #parentReference>
  <child-component Xdirective="parentReference">
    anything this component contain but with a reference to parent.
  </child-componet>
</parent-component>

2 个答案:

答案 0 :(得分:0)

您可以使用组件的exportAs声明访问对组件的引用。

@Component({
    ....
    exportAs: 'parentReference'
})
export class ParentComponent {}

@Component({...})
export class ChildComponent {
    @Input()
    public parent: ParentComponet;
}

您必须将导出的值parentReference分配给模板值,然后将其传递给输入参数。

<parent-component #ref="parentReference">
   <child-component [parent]="ref">
      anything this component contain but with a reference to parent.
   </child-componet>
</parent-component>

您还可以通过构造函数注入父组件,但是如果子组件位于<ng-content>块中,则此方法将无效。

@Component({...})
export class ParentComponent {}

@Component({...})
export class ChildComponent {
    constructor(parent: ParentComponent) {
       ...
    }
}

答案 1 :(得分:0)

如果您的孩子有一个唯一的父级(始终是同一类Component的孩子),则可以使用@Optional()@Host(),请参见stackblitz

export class HelloComponent implements OnInit  {
  @Input() name: string;
  constructor(@Optional() @Host() private parent:AppComponent){
  }
  ngOnInit()
  {
    console.log(this.parent.anotherVariable)
  }
}

但是,如果您可以使用@Input ot @Output解决问题,那么这是更好的解决方案

相关问题