javascript - 无法使用@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
解决方案
要将数据从孩子发送到父母使用事件(而不是 ViewChild) - 例如在孩子中:
@Output() public myevent = new EventEmitter<any>();
...
fireEvent() {
this.myevent.emit({'some':'data'});
}
并在父模板中
<child-component (myevent)="handleEvent($event)">...</child-component>
handleEvent(data)
您的 pratent 函数在哪里,它将从孩子那里获取发出的数据
推荐阅读
- angular - Angular 10:在视图上显示用户信息
- linux - Linux:检测对进程内存区域的所有写入
- python - Plotly:如何将交互式绘图保存为 pdf 文件?
- android - Android:屏幕截图为 org.webrtc.SurfaceViewRenderer 获取黑色图像
- sorting - Elastic Search 中的聚合和排序
- php - 为什么某些资产文件在 https 中的重定向太多?
- python - 如何找到函数参数输入的长度?
- python - 如何从 atan 转换为 atan2?
- modelica - 错误:vessel_ps_static 修改中的数组大小不匹配,预期大小为 [0],绑定表达式的大小为标量 - Modelica
- liferay-7 - 我可以删除 Liferay 7 默认的“全局”和“Liferay”站点吗?