angular 5-从父组件获取子组件的实例

时间:2018-12-11 19:25:14

标签: angular angular5 angular6

我的组件层次结构如下。

Parent Component A 
  -> Child Component B (child of component A)
      -> Child component C (child of component B)

我们如何从父组件A获取对组件c的引用?我尝试使用view child从父级访问子级组件C,但未定义。

注意:子组件来自某个第三方库。我无法更改这些文件

stackblitz.com/edit/angular-bpmwxz

2 个答案:

答案 0 :(得分:0)

@ViewChild将起作用。但是,我们不知道它的组织方式或组件B的模板如何工作,因此,如果有模板指令,组件B正在使用,则您必须@ViewChild(ComponentCTypeToken)而不是使用模板变量。

但是,由于我们不知道组件B如何呈现模板(或如何使用这些组件),如果组件C嵌套在组件A模板中的组件B中,则很有可能组件B正在呈现自己的模板通过内容投影;在这种情况下,它必须是@ContentChild

答案 1 :(得分:0)

您可以通过链接引用解决此问题。

Parent Component A { 
      holds the reference of Chil Component B;
      calls the ChildB.function();
}
    -> Child Component B { 
          holds the reference of Child Component C <-- hope this is the library component
          calls the ChildC.function();
        }
          -> Child component C {
            function();
          }

代码示例

export class AppComponent {
  name = 'Angular';

  @ViewChild(SampleOneComponent)
  sampleOne: SampleOneComponent;


  getInstanceOfChild() {
    this.sampleOne.getInstanceOfChild();
  }
}

export class SampleOneComponent implements OnInit {

 @ViewChild(SampleTwoComponent)
  sampleOne: SampleTwoComponent;
  constructor() { }

  ngOnInit() {
  }

  getInstanceOfChild() {
    this.sampleOne.libFn();
  }

}

export class SampleTwoComponent implements OnInit {
  title: string = "yeahhh";
  constructor() { }

  ngOnInit() {
  }

  libFn() {
    console.log('Im in sample two');
  }

}

带有chagnes https://stackblitz.com/edit/angular-jnhc5v的Stackblitz网址

相关问题