首页 > 解决方案 > 无法使用@ViewChild Angular 7将数据从子级传递给父级

问题描述

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

我有这个代码

管理布局.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);
}  

和代码来自

部落组件.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);

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

标签: javascriptangularparent-childviewchild

解决方案


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

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

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

并在父模板中

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

handleEvent(data)您的 pratent 函数在哪里,它将从孩子那里获取发出的数据


推荐阅读