首页 > 解决方案 > angular 8 - 从父组件获取子组件的实例

问题描述

我有一个组件层次结构如下。

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

我们如何从间接父组件 A 中获取对组件 c 的引用?我尝试使用视图子项从父项访问子组件 C,但未定义。

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

stackblitz.com/edit/angular-bpmwxz

标签: angularangular6angular8

解决方案


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

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');
  }

}

Stackblitz 网址与 chagnes https://stackblitz.com/edit/angular-jnhc5v


推荐阅读