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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…