Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Call existing component from another component

I'm creating an app with Angular 2 using the routing features, and I have a popup component that is rendered by one of the higher up routes, and I want to open it on a click event in a component that is rendered by one of the deeper routes.

For example, let's say I have a base router with a template containing the popup:

@Component({
    selector: 'application',
    template: '<router-outlet></router-outlet><popup-component></popup-component>',
    directives: [PopupComponent]
})
@RouteConfig([
    { ... },
    { ... }
])
export class AppRoute { }

And a simple popup component with an open method:

@Component({
    selector: 'popup-component',
    template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
    public isVisible: boolean = false;
    show() {
        this.isVisible = true;
    }
}

How can I call this show method on that specific PopupComponent that was already rendered by the AppRoute from another component that resides somewhere down in the routing tree?

I have tried using dependency injection like this:

@Component({
    selector: 'my-component',
    template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
    constructor(private popup: PopupComponent) { }
    showPopup() {
        this.popup.show();
    }
}

But this just creates a new instance of the PopupComponent that isn't actually rendered yet. How can I call the one that is rendered by the AppRoute?

like image 516
Bliss Avatar asked Apr 06 '16 16:04

Bliss


1 Answers

You need a shared service

import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Rx';
export class PopupService{
   show:Subject<boolean> = new Subject();
}

Add the service to providers in AppRoute

@Component({
    providers:[PopupService],
    selector: 'application',
    ...
])
export class AppRoute { }

Inject the service to popup-component and subscribe to the show subject.

@Component({
    selector: 'popup-component',
    template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
    public isVisible: boolean = false;
    constructor(private popup: PopupService) {
      popup.show.subscribe( (val:boolean) => this.isVisible = val );
    }
}

Inject it to any component where you want to show the popup, call next on the show subject;

@Component({
    selector: 'my-component',
    template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
    constructor(private popup: PopupService) { }
    showPopup() {
        this.popup.show.next(true);
    }
}
like image 54
Abdulrahman Alsoghayer Avatar answered Nov 15 '22 05:11

Abdulrahman Alsoghayer