Slowly getting to grips with angular 2 but I\'ve come to dead end on one particular issue.
If you have this arrangement;
There's also the possibility of just using a shared service to communicate between different components, e.g. via a messenger service like this:
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);
}
}
Parent Component
export class ParentComponent {
constructor(private messengerService: MessengerService) { }
addEntity() {
this.messengerService.buttonClicked(true);
}
}
Child Component
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();
}
}
This would be a clean way to decouple the components and rely on a messenger service (that you could subscribe to in multiple components, wherever it is required)
Well if I understand well your question try this: put a return value on the addEntity() method, can be an string, or something that you know the kind of thing that you are adding (heroes/contacts/pets). Then on the main template put a local variable that takes the return of the addEntity() method like this:
<button (click)='#type_added = addEntity()>Add</button>
then you can pass that "#type_added" local variable to the other component like this:
<router-outlet [added] = #type_added></router-outlet>
and you must declare in your router-outlet component (.ts) the variable "added" whidth the @Output.