首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从角9中的子组件中访问父组件

如何从角9中的子组件中访问父组件
EN

Stack Overflow用户
提问于 2020-03-30 08:35:01
回答 1查看 10.8K关注 0票数 3

问题

  • 无法从父级子通信中使用用户viewContainerRef。

代码在角8.2中工作

代码语言:javascript
复制
 this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component;

错误

错误TypeError:无法读取未定义的属性“componentView”

公共Api https://angular.io/api/core/ViewContainerRef

代码语言:javascript
复制
    this.viewContainerRef.get(0) still i got null

我需要从子组件访问父组件。

吴版

代码语言:javascript
复制
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

任何建议都是受欢迎的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-01 08:49:52

您不应该(肯定)访问第三方库的私有成员,以避免您遇到的麻烦。幸运的是,如果我猜对了你想做的事情,你可以做一些事情来避免访问这些私人成员。我将展示3种解决方案,其中2种是在这个答案末尾引用的stackblitz上实现的。

让我们假设您有这样的场景:一个父组件,它有一个propertyA,您想通过某种原因直接访问子组件。

父组件:

代码语言:javascript
复制
@Component({
  template: `
    <child></child>
  `
})
export class ParentComponent { propertyA: string; }

案例A:直接在子女体内注射父母

代码语言:javascript
复制
@Component({selector: 'child', ...})
export class ChildComp {
  constructor(private _parent: ParentComponent) { this._parent.propertyA = 'some value'; }
}

案例B:让父母通过孩子的ViewContainerRef

代码语言:javascript
复制
@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:让父母通过孩子的注射器,直接注射

代码语言:javascript
复制
@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),

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60926745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档