[英]How to Access Parent Component from Child Component in Angular 9
问题
代码在 Angular 8.2 中工作
this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component;
错误
错误类型错误:无法读取未定义的属性“componentView”
公共 API https://angular.io/api/core/ViewContainerRef
this.viewContainerRef.get(0) still i got null
我需要从子组件访问父组件。
吴版
Package Version
------------------------------------------------------
@angular-devkit/architect 0.900.7
@angular-devkit/core 9.0.7
@angular-devkit/schematics 9.0.7
@schematics/angular 9.0.7
@schematics/update 0.900.7
rxjs 6.5.3
无法在 stackblitz 中复制该问题
https://stackblitz.com/edit/angular-testangular9-communicating-x
问题
ViewContainerRef 在 Angular 9 中不起作用
工作视图ContainerRef
在 Angular 9 中不工作 ViewConatinerRef
任何建议都是最受欢迎的。
您不应该(绝对)完全访问 3rd 方库的私有成员以避免遇到麻烦。 幸运的是,如果我做对了你想做的事情,你可以做一些事情来避免访问这些私人成员。 我将展示 3 个解决方案,其中 2 个在本答案末尾引用的 stackblitz 上实现。
假设您有这样的场景:一个父组件具有一个propertyA
,出于某种原因您想直接在子组件中访问它。
@Component({
template: `
<child></child>
`
})
export class ParentComponent { propertyA: string; }
@Component({selector: 'child', ...})
export class ChildComp {
constructor(private _parent: ParentComponent) { this._parent.propertyA = 'some value'; }
}
ViewContainerRef
获取父级@Component({selector: 'child', ...})
export class ChildComp {
constructor(private viewContainerRef: ViewContainerRef) {
const _injector = this.viewContainerRef.parentInjector;
const _parent: ParentComponent = _injector.get<ParentComponent>(ParentComponent);
this._parent.propertyA = 'some value';
}
}
这是重要的部分:角度注入器的存在正是为了做你想要的,所以不要试图自己获取对组件的引用,正确的做法是找出如何找到一个注入器来为你搜索。 请记住,注入器以层次结构分布,如果注入器无法解析符号,它会要求其父注入器尝试递归解析它,直到到达根注入器。 这导致我们采用第三种方法,直接获取组件的注入器:
@Component({selector: 'child', ...})
export class ChildComp {
constructor(private _injector: Injector) {
const _parent: ParentComponent = this._injector.get<ParentComponent>(ParentComponent);
this._parent.propertyA = 'some value';
}
}
情况 B 和 C 之所以有效,是因为您的组件以父-n-子关系分布在组件树中,并且在某些时候它们将在声明/导入它们的模块中有一个公共注入器。
我已经修改了您的 stackblitz以显示这两种解决方案(案例 A 用于 a 组件,案例 B 用于 b 组件),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.