Search code examples
javascriptangularmodal-dialogviewchild

Angular 4 - Access to father element view is undefined with @ViewChild


I need to create a modal to manage errors. So I suppose that the best solution is to put this modal in my app.component so that I can use a single modal in my project:

<my-dialog #MyErrorDialog>
    ...
</my-dialog>

now I need to open this modal in many components or services when an http code occurs but with the reference id:

@ViewChild('MyErrorDialog') MyErrorDialogReference: MyDialog; 

MyErrorDialogReference in my child component/service is undefined because the modal is in the app component.

I don't want to use @Input/@Output.


Solution

  • You can use service as:

    ErrorService

    public errorMessage = new Subject<string>();
    setErrorMessage(value: string) {
        this.errorMessage.next(value);
    }
    

    any other component Notify service about error

    constructor(public errorService: ErrorService) { }
    setMessage(message) { // call this method whenever you get error
        this.errorService.setErrorMessage(message);
    }
    

    app.component receive error in App component

    errorMessage: string;
    errorSubscription: Subscription;
    constructor(public errorService: ErrorService) { }
    ngOnInit() {
        this.errorSubscription = this.errorService.errorMessage.subscribe(
            (message) => {
                this.errorMessage = message;
                // open dialog with message
            }
        );
    }
    ngOnDestroy() {
        this.errorSubscription.unsubscribe();
    }