Search code examples
angulartypescriptangular-servicesangular-components

Angular - Updating component value, when service value changes


I have multiple components (in an NgFor loop) that call the same service.

What I would like is that when one component changes a value in that same service, that new value then gets sent to every component that calls that service and subsequently updates that value in a component variable.

I hope that makes sense.

If you need some more information, please let me know.


Solution

  • Instead of a BehaviorSubject (which are often overkill in simple scenarios), you can use simple getters:

    Service has some data to share:

    export class ProductParameterService {
      showImage: boolean;
      filterBy: string;
    
      constructor() { }
    
    }
    

    Components just use a getter and any template variable bound to the property is automatically updated when the service value changes:

    get showImage(): boolean {
        return this.productParameterService.showImage;
    }
    

    In template:

                            <img *ngIf='showImage'
                                 [src]='product.imageUrl'
                                 [title]='product.productName'>
    

    If any component anywhere in the application uses the service to change the value of showImage, the view will automatically update (leveraging Angular's built in change detection).