简体   繁体   English

无法使用@ViewChild Angular 7将数据从子级传递到父级

[英]Can't pass data from Child to Parent using @ViewChild Angular 7

Hi I can't pass my data from child to parent using @ViewChild 嗨,我无法使用@ViewChild将数据从孩子传递给父母

I have this code from 我有这个代码

admin-layout.component.ts 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);
}  

and code from 和来自的代码

tribecomponent.ts tribecomponent.ts

messagetwo:string = "true";

the error is 错误是

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)

the first console was undefined console.log( this.getRoute); 第一个控制台是未定义的console.log( this.getRoute);

the second one was the error above console.log("primaryColorSample:", this.message); 第二个是console.log("primaryColorSample:", this.message);上面的错误console.log("primaryColorSample:", this.message);

btw admin-layout is kind of my app component html so I use router outlet to navigate to tribe component. btw admin-layout是我的应用程序组件html的一种,因此我使用路由器插座导航到部落组件。 Is it the reason why it can't see tribe as its child? 这是为什么它不能将部落视为孩子的原因吗? here's a sample how my layout work Creative Tim's Argon Dashboard Angular 这是我的布局如何工作的示例Creative Tim的Argon仪表板角度

To send data from child to parent use events (not ViewChild) - eg in child: 要将数据从子级发送到父级使用事件(不是ViewChild),例如在子级中:

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

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

and in parent template 并在父模板中

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

where handleEvent(data) is your pratent function which will get emited data from child 其中handleEvent(data)是您的强大函数,将从子级中获取发射的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM