问题
代码在Angular 8.2中有效
this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component;
错误
错误TypeError:无法读取未定义的属性'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中不起作用
工作ViewContainerRef
Angular 9中的ViewConatinerRef不起作用
任何建议都是最欢迎的。
您不应该(绝对)完全访问第三方库的私人成员,以免遇到麻烦。幸运的是,如果我做对了您想做的事情,您可以做一些事情来避免访问这些私人成员。我将展示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起作用的原因是,您的组件以父-子-子关系分布在组件树中,并且在某些时候,它们在声明/导入它们的模块处具有公共的注入器。
我已经修改了您的stackblitz以显示这两种解决方案(案例A用于a组件,案例B用于b组件),
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句