cyber_angel
cyber_angel

Reputation: 303

Communicating between child to parent component in Angular 8

I am trying to communicate to my parent controller that a new item have been added in its child component. I am aware that for this I have to use @Output and event emitters, and I am using them, but it doesn't seem to be working. Is there another way to accomplish this?

Upvotes: 1

Views: 2203

Answers (3)

cyber_angel
cyber_angel

Reputation: 303

I tried using @Output and event emitters (plus modified my project) and it worked.
Turns out I didn't need to add a type to the event emitter:

@Output() public namespaceCreated = new EventEmitter<Namespace[]>();

Upvotes: 0

G. Stoynev
G. Stoynev

Reputation: 7791

Yes, there is. You can create a "service" and have a multi-cast observable / subject (e.g. BehavioralSubject<>) push new values.

Here's a good starting point (btw, check out the other methods, too):

Parent and children communicate via a service

Upvotes: 1

Tony
Tony

Reputation: 20122

You can use Subject to do that. Here is the link to my blog for your ref

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

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    constructor() {}

    sendMessage(message: any) {
        this.subject.next(message);
    }

    getData() {
        return this.subject.asObservable();
    }
}

I defined 2 method here. The first method using next() to send message to the next subcriber. So in your component you just need to simply subscribe like this to get the data

private subscription$: Subscription;

public ngOnInit(): void {
  this.subscription$ = this.messageervice
            .getData()
            .subscribe(data => { console.log(data); })
}

public ngOnDestroy(): void {
    this.subscription$.unsubscribe();
}

Upvotes: 0

Related Questions