【发布时间】: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