Angular 4 - @ViewChild component is undefined

后端 未结 1 1994
夕颜
夕颜 2020-12-10 23:37

I have a toast notification component called ToastComponent which I want to call from any other component. I implemented it like this:

ToastCompon

相关标签:
1条回答
  • 2020-12-11 00:06

    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();
      }
    }
    
    0 讨论(0)
提交回复
热议问题