angular - 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
解决方案
您可以通过链式引用解决此问题。
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
推荐阅读
- json - 如何将完整的 json 数据映射到我的代码中?现在我一次只能做一个条目
- java - 如何使用 Selenium RemoteWebDriver 设置 HTTP_PROXY?
- javascript - 如何检测由 Enter 按键触发的浏览器中的鼠标点击?
- angular - 使用 Ionic Angular 如何将值从服务传递到页面
- delphi - 构建带有误报的 exe 文件(Delphi)
- python-3.x - 如何用一张图像预测训练好的模型?
- excel - 如何验证 Twitter ID 的 URL 以了解其当前状态
- python - 为什么 kivy 在 Visual Studio 代码中不起作用?
- migrate - 在 .Net 5 中替代 ServiceHost
- javascript - 用 Python BeautifulSoup 解析 JS 变量和函数