无法使用@ViewChild Angular 7

时间:2019-07-08 08:51:19

标签: javascript angular parent-child viewchild

嗨,我无法使用@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

的示例

1 个答案:

答案 0 :(得分:0)

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

$(document).on("focusin","input[type='text']",function(event) {
    alert('element was focused', {event:event});
    // let element = $(event.currentTarget); 
});

和父模板中

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

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

其中<child-component (myevent)="handleEvent($event)">...</child-component> 是您的强大功能,将从子级发出数据