Angular 2 => report an event route component in an application component

Getting to angular 2 slowly, but I was stumped by one specific issue.

If you have this agreement,

<parent>
    <child/>
</parent>

I can notify the child of the parent changes using @Input () and make him listen to the changes. I can notify the parent of changes in the child using @Output () and EventEmitters.

What I'm looking at now notifies the routable component (the component that dynamically loads when the link is clicked) about a specific event that occurs in the main appComponent. See the example below;

<app>
    <button (click)='addEntity()>Add</button>
    <router-outlet></router-outlet>
</app>

I want to be able to notify a component that is loaded on a socket router by a button click.

(// ..), . (, ContactComponent), // (, contact-detail.component).

?

+1
2

, . :

MessengerService

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class MessengerService {
    private messageSource: BehaviorSubject<boolean> = new BehaviorSubject(true); 
    public message = this.messageSource.asObservable();
    public buttonClicked(value: boolean) {
        this.messageSource.next(value);
    }
}

export class ParentComponent {
    constructor(private messengerService: MessengerService) { }
    addEntity() {
        this.messengerService.buttonClicked(true);
    }
}

import { Subscription } from 'rxjs/Rx';
export class ChildComponent implements OnInit, OnDestroy {
    private messageSubscription: Subscription;
    constructor(private messengerService: MessengerService) { }
    ngOnInit() {
        this.messageSubscription = this.messengerService.message.subscribe(m => {
            // Act upon the click event
        });
    }
    ngOnDestroy() {
        this.messageSubscription.unsubscribe();
    }
}

( , )

+3

, , : addEntity(), -, , (// ). , addEntity() :

<button (click)='#type_added = addEntity()>Add</button>

"#type_added" :

<router-outlet [added] = #type_added></router-outlet>

- (.ts) "" whidth @Output.

0

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


All Articles