Aakriti.G
Aakriti.G

Reputation: 686

How to update parent component from child component in Angular 2

I want to update parent component when child component is updated. I was trying to achieve this using event emitter but I am using router outlet to call the child component. I have no idea how to do that.

Can anyone please guide me what should I do to get this?

Thanks

Upvotes: 3

Views: 2763

Answers (1)

Adeeb basheer
Adeeb basheer

Reputation: 1490

You cannot directly update parent component from a child component. But you can create a service that can interact from any component to any other component as below.

Create a file communication.service.ts

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

@Injectable()
export class CommunicationService {
    constructor() { }

    private emitChangeSource = new Subject<any>();

    changeEmitted$ = this.emitChangeSource.asObservable();

    emitChange(data: {}) {
        this.emitChangeSource.next(data);
    }

}

In child component

import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./child.component.html`,
    styles: ['child.component.css']
})
export class ChildComponent{
    constructor(private _communicationService: CommunicationService) { }

    onSomething() {
        this._communicationService.emitChange({proprty: 'value'});
    }
}

In parent component

import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./parent.component.html`,
    styles: ['./parent.component.css']
})

export class ParentComponent {    
    constructor( private _communicationService: CommunicationService ) { 
        _communicationService.changeEmitted$.subscribe(data => {
        // ...
        })
    }
}

Upvotes: 5

Related Questions