suchi
suchi

Reputation: 83

How to communicate between sibling components

I am new to angular, please let me know if I am doing anything wrong or following a wrong approach.

I have a foodDetails component where on click of buynow button, food is pushed into an array.

ShopDataService is a common service used between foodDetails component and headerComponent, in header component i want to keep displaying the length of product array everytime when user click on buynow button in foodDetails component. So how to notify the header component when buynow is clicked in foodDetails component.

export class ShopDataService {
    products: any[];
    constructor() {
        this.products = [];
    }
    add(product: any) {
        this.products.push(product);
    }
    get() {
        return this.products;
    }
}

FoodDetails Component:

buynow(product){
    this.ShopDataService.add(product);
}

Here is a structure of my html container:

<div class="container">
  <prac-header></prac-header>
  <router-outlet></router-outlet>
</div>

The header component is prac-header, whereas foodDetail Component in router-outlet

Upvotes: 3

Views: 1572

Answers (1)

Maciej Treder
Maciej Treder

Reputation: 12350

The best way to communicate between sibling components (in my opinion) can be done by using service:

service

export class Service {
    private valueObs: BehaviorSubject<string> = new BehaviorSubject<string>(null);

    public setValue(value: string):void {
        this.valueObs.next(value);
    }

    public getValue():Observable<string> {
        return this.valueObs;
    }
}

first component

@Component({
    selector: 'component-one',
    template: `<button (click)="buttonClicked()">clicke me</button>`
})
export class ComponentOne {
    constructor(private service: Service){}

    public buttonClicked():void {
        this.service.setValue("someValue");
    }
}

second component

@Component({
    selector: 'component-two',
    template: `{{value | async}}`
})
export class ComponentTwo {
    public value: Observable<string>;
    constructor(private service: Service){}

    ngOnInit() {
        this.value = this.service.getValue();
    }
}

Upvotes: 2

Related Questions