Angular 2: calling an existing component from another component

I am building an application with Angular 2 using routing functions, and I have a pop-up component that displays one of the routes listed above, and I want to open it with a click event in a component that displays one of the deeper routes.

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

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

And a simple open method popup component:

 @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 this particular PopupComponent that has already been shown by AppRoute from another component that is located somewhere in the routing tree?

I tried using dependency injection as follows:

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

But it just creates a new PopupComponent instance that is not yet displayed. How can I call the one that appears in AppRoute?

+5
source share
1 answer

You need a shared service

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

Add Service Providers to AppRoute

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

Add the service to the popup-component and subscribe to the display topic.

 @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 ); } } 

Add it to any component where you want to display a pop-up window, call next on the show topic;

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

Source: https://habr.com/ru/post/1246571/


All Articles