Angular 4 - @ViewChild component is undefined

不羁的心 提交于 2019-11-28 11:48:35

Since in your case, the ToastComponent is used in the grand parent (AppComponent), that's why you are getting this error. One way to avoid this error is to use Subject defined in some shared service. I am using that approach in my project to show toast notifications. Here is how you can do it:


Keep your <llqa-toast></llqa-toast> in app.component.html.

Define a service to basically emit an event and subscribe to that event in your ToastComponent. For example,

UtilityService:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class UtilityService {

    public OnShowToast = new Subject<boolean>();

    public showToast(): void {
        this.OnShowToast.next(true);
    }
}

You need to inject this service in your AppModule providers. Now subscribe to the OnShowToast event in your ToastComponent.

ToastComponent:

import { UtilityService } from './path/to/the/utility.service';
export class ToastComponent implements OnInit {

  constructor(private readonly utilityService: UtilityService) { }

  ngOnInit() { 
     this.utilityService.OnShowToast.subscribe(value =>
        {
            this.showToast();
        });
  }

  private showToast() {
    // some code
  }
}

Now, you can call the showToast() method of the UtilityService from any component you want. For example,

UserManagementComponent

export class UserManagementComponent implements OnInit {

  // You dont need this now
  // @ViewChild(ToastComponent) toast: ToastComponent;

  constructor(private readonly utilityService: UtilityService) {}

  someSaveMethod() {
    this.utilityService.showToast();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!