【问题标题】:Can't pass data from Child to Parent using @ViewChild Angular 7无法使用@ViewChild Angular 7将数据从子级传递给父级
【发布时间】:2019-07-08 08:51:19
【问题描述】:

您好,我无法使用 @ViewChild 将我的数据从孩子传递给父母

我有这段代码来自

admin-layout.component.ts

@ViewChild(TribeComponent)
 getRoute :TribeComponent; 

ngAfterViewInit() {
  console.log( this.getRoute);
  this.message = this.getRoute.messagetwo;
  console.log('Values on ngAfterViewInit():');
  console.log("primaryColorSample:", this.message);
}  

和来自

的代码

tribecomponent.ts

messagetwo:string = "true";

错误是

TypeError: Cannot read property 'messagetwo' of undefined
at AdminLayoutComponent.push../src/app/layouts/admin-layout/admin-layout.component.ts.AdminLayoutComponent.ngAfterViewInit (admin-layout.component.ts:45)
at callProviderLifecycles (core.js:22416)
at callElementProvidersLifecycles (core.js:22390)
at callLifecycleHooksChildrenFirst (core.js:22380)
at checkAndUpdateView (core.js:23316)
at callViewAction (core.js:23548)
at execEmbeddedViewsAction (core.js:23511)
at checkAndUpdateView (core.js:23308)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)

第一个控制台未定义console.log( this.getRoute);

第二个是上面console.log("primaryColorSample:", this.message);的错误

btw admin-layout 是我的应用程序组件 html 的一种,所以我使用路由器插座导航到部落组件。这就是它不能视部落为孩子的原因吗? 这是我的布局如何工作的示例Creative Tim's Argon Dashboard Angular

【问题讨论】:

  • 您的模板中是否有任何*ngIf 在您要查询的孩子上方?
  • 不,我没有@Reactgular
  • 您的模板是否有<ng-content>,因为您需要使用@ContentChild
  • @Reactgular 如何使用它?
  • 我调查了您的项目结构,admin-layout.component 既没有作为 ViewChild 也没有作为 ContentChild 的 TribeComponent。它被放置在 router-outlet 下,它成为 DOM 树中 admin-layout.component 的子节点,而不是 Angular 的 View Hierarchy 中。关于这个有一个discussion。并且有很好的解释here

标签: javascript angular parent-child viewchild


【解决方案1】:

将数据从孩子发送到父母使用事件(不是 ViewChild) - 例如在孩子中:

@Output() public myevent = new EventEmitter<any>();

...
fireEvent() {
  this.myevent.emit({'some':'data'});
}

在父模板中

<child-component (myevent)="handleEvent($event)">...</child-component>

handleEvent(data) 是您的 pratent 函数,它将从子节点获取发出的数据

【讨论】:

  • 有什么问题?
  • 未捕获错误:模板解析错误:'app-tribe' 不是已知元素:1. 如果 'app-tribe' 是 Angular 组件,则验证它是否是该模块的一部分跨度>
  • 你的组件有问题(不是事件)——在stackoverflow上写一个单独的问题
  • 请通过我提供的链接查看文件结构
猜你喜欢
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多