0

I am doing an Angular2 project with nested multiple component. I managed to send some data from immediate child component to immediate parent component. But in case of 3 nested component, how can I change or send data to multiple parent components?

For example, in following image, No 1 is message-center component. No 2 is message-list component which is called from No 1 component's html through selector < message-list [messageList]="mails" >.

No 3 is a message-detail component whose parent is No 2. Now in No 3 component if we delete one selected message from Inbox, this message will also be deleted from message-list component's which is no 2 and in No 1 component, “Deleted” labeled no will also be changed to "Deleted(1)". Now how we can change the multiple parents for a change event in 2 level nested child component which is No 3?

enter image description here

  • I can suggest you use NgRx to manage your state. It's not easy but once you mastered it, your development flow will be much more easier. This problem can be solved easily with NgRx/store – Envil Jul 05 '18 at 09:31
  • you can use rxjs subject or use ngrx/store or ngrx/redux – Chellappan வ Jul 05 '18 at 09:35

2 Answers2

1

You can use BehaviorSubject in a service with for exemple a Message service (don't forget to add do rxjs operator if you :

 @Injectable()
 export class MessageService {
     public $messages: BehaviorSubject<Message[]> = new BehaviorSubject<Message[]>([]);
     public getMessages() {
        const url = 'your url';
        return this.http.get(url).do(messages => this.$messages.next(messages));
     }
 }

And then to access your data in a component inject the service and use the method like :

 msgService.$messages.subscribe(messages => this.messages = messages); // update data each time next is called
 msgService.getMessages().subscribe(); // do the http call

then when you delete a message you just need to update the list using next :

const newList = this.messages.filter(message => message.id !== deletedMessage.id);
msgService.$messages.next(newList);

It will automaticly update the data. I hope it helps.

Julien METRAL
  • 1,894
  • 13
  • 30
  • When using this method, don't forget to [unsubscribe](https://stackoverflow.com/a/41177163/2526437) when the component is destroyed :) – cyberpirate92 Jul 05 '18 at 09:47
0

I have done the notifying job by invoking EventEmitter in component 3. To make an action in component 1 for some action in component 3, I notified component 2 as it is immediate parent of component 3, to notify its parent component 1. It seems bit messy but its easier.