Home > Enterprise >  Angular - trigger an event based on a variable change
Angular - trigger an event based on a variable change

Time:12-20

I have a list of items that is set in the service and is called in the ngOnInit():

async ngOnInit(){
   this.items = await this.service.getItems();
}

and this list is rendered using the directive *ngfor.

However, now I need to refresh the items list when there is any change in a variable. So I need an event that runs only when a certain variable (lets called it itemCategories) changes its value lets.

How can I achieve this?

Angular version is 12 and I am new to this

CodePudding user response:

Based on your short explanation here is a general solution:

wrap your items assignment in a method and call this method when you set the itemCategories value.

async ngOnInit(){
   this.setItems();
}

setItems(){
   this.items = await this.service.getItems();
}

setItemCategories(value){
   this.itemCategories = value;
   this.setItems();
}

CodePudding user response:

fill your data in behaviourSubject then subscribe to it, now your behaviourSubject method will be called whenever you data get changed, here is an example:

I declare my behaviourSubject like these:

  private _resetForm$ = new BehaviorSubject<boolean>(false);


      public set setResetForm(resetStatus: boolean) {
        this._resetForm$.next(resetStatus);
      }
    
      public get resetForm(): Observable<boolean> {
        return this._resetForm$.asObservable();
      }

then I change it here:

  this.setResetForm = true;

now i will get event from here because setResetForm have changed so i will get my event from it:

  ngOnInit(): void {
    this.resetForm.subscribe((res: boolean) => {
      if (res) {
        console.log(res);
      }
    });
  }

good luck!

  • Related