After selecting drop down from header how to change the content of other component in Angular

After selecting drop down from header how to change the content of other component in Angular

Problem Description:

I was trying to build a multi-product application.
Using a drop-down in the header, the user can choose which application data to be shown.

Below is the code snip it of my code of my drop-down in header after every click/ change will call the function change Product (passing the selected product name)

<ul class="dropdown-menu pull-right" style="margin-left:-100px;" ngbDropdownMenu aria-labelledby="languageDropDown">
                  <li *ngFor="let a of products " class="dropdown-item text-center" (click)="changeProduct(a)"style="cursor:pointer;" data-toggle="collapse" data-target=".navbar-collapse" (click)="isCollapse = !isCollapse">
                      {{a.name}}
                  </li>
              </ul>

Here is the function code
Explanation of below code. In this function, I want the values of other function should be changed. I was thinking to call ngOnInit() but seems like the changes are not being reflected until the page is being reloaded manually. Hence i had to use window.location.reload() to reload function but this is not an idea solution .

 changeProduct(product:Product) {
    this.app=product.name;
    this.cookieService.set('currentAppName',""+product.productCode);
    this.cookieService.set('productID',product.id);
    this.OtherComponent.ngOnInit();
    window.location.reload()
  }


Hope someone can suggest me the correct way how to change the other component values after making changes in header in Angular 13

Solution – 1

So, here is a minimal example. The "MyService" hold the value (simple a string in this example). In the AppComponent we bind the value from the service with a Subscription. This Subscription can be in every component/child route what ever you want. So if the value in the service has changed all components get the new value.

Here is the Stackblitz link.

Greetings, Flo

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject