问题
代码在角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不工作在角度9
工作ViewContainerRef

在角9中不工作ViewConatinerRef

任何建议都是受欢迎的。
发布于 2020-04-01 08:49:52
您不应该(肯定)访问第三方库的私有成员,以避免您遇到的麻烦。幸运的是,如果我猜对了你想做的事情,你可以做一些事情来避免访问这些私人成员。我将展示3种解决方案,其中2种是在这个答案末尾引用的stackblitz上实现的。
让我们假设您有这样的场景:一个父组件,它有一个propertyA,您想通过某种原因直接访问子组件。
父组件:
@Component({
template: `
<child></child>
`
})
export class ParentComponent { propertyA: string; }案例A:直接在子女体内注射父母
@Component({selector: 'child', ...})
export class ChildComp {
constructor(private _parent: ParentComponent) { this._parent.propertyA = 'some value'; }
}案例B:让父母通过孩子的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';
}
}这是最重要的部分:角度喷射器的存在正是为了做你想做的事情,所以,与其试图自己获得对组件的引用,正确的做法是找到一个喷射器来为你进行搜索。请记住,注入器在层次结构中的分布方式是这样的:如果一个注入器不能解析一个符号,它会要求他的父注入器尝试递归地解析它,直到到达根注入器为止。这就引出了第三种方法,直接获得组件的注入器:
案例C:让父母通过孩子的注射器,直接注射
@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-子关系中的一个组件树中,并且在某个时候,在声明/导入它们的模块中,它们将有一个通用的注入器。
我修改了你的堆栈闪电战以显示这两种解决方案(a组件上使用的案例A,b组件上使用的案例B),
https://stackoverflow.com/questions/60926745
复制相似问题