Trigger function on field change

Viewed 289

I want to trigger a function if a flag variable is changed. I read about ngOnChanges only works with @Input whereas I have a variable.

isFormCompleted: boolean = false;

ngOnInit() {
  this.checkComplete();
}

checkComplete() {
  /**
  * Checks if all conditions are valid and then turns the flag variable to true
  **/
  this.isFormCompleted = true;
}

Now I want to fire a function as soon as the flag variable is changed to true. How do I achieve that?

3 Answers

Using getters and setters:

private _isFormCompleted: boolean = false;

get isFormCompleted(): boolean {
  return this._isFormCompleted;
}

set isFormCompleted(value: boolean) {
  this._isFormCompleted = value;
  if (this._isFormCompleted) {
    this.functionCall();
  }
}

You can use rxjs for that, creating a Subject which is a stream that you can subscribe on when it changes. Angular should have the packages by default

isFormCompleted$: Subject = new Subject<boolean>(false);

ngOnInit() {
  this.isFormCompleted$.subscribe({
    // Here you can add your callback and do with the changing value whatever you want
    next: (v) => console.log(`value: ${v}`)
  });
}

checkComplete() {
  this.isFormCompleted$.next(true);
}

This will always be executed when the subject changes its value. You can trigger it by calling:

this.isFormCompleted$.next(true);

Documentation: https://rxjs.dev/guide/subject

You may try this way also.

isFormCompleted: boolean = false;

ngOnInit() {
  this.checkComplete();
}

checkComplete() {

  if (this.isFormCompleted) {
      this.isFormCompleted = !this.isFormCompleted
   }
     
}
Related