Вызов метода при изменении определенного свойства

#angular

Вопрос:

У меня есть метод, который я хочу запускать в любое время, когда изменяется определенное свойство в моем компоненте. Значение получено из входных данных другого компонента.

Всякий myValue раз, когда что-то меняется, я хотел бы вызвать myMethod метод.

 @Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {
  @Input() myValue: any;

  myValue: any;

  constructor() {}

  private myMethod() {
    // Called when this.myValue changes
  }
}    
 

Комментарии:

1. Внедрите ngOnChages и протестируйте их на предмет изменений

Ответ №1:

Вы можете достичь этого с помощью ngOnChanges крючка жизненного цикла или с помощью сеттера в сочетании с @Input

Вот решение с помощью ngOnChanges

 import { OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnChanges {
  @Input() myValue: any;

  constructor() {}

  ngOnChanges(changes: SimpleChanges) {
   if(changes amp;amp; changes.myValue) {
     this.myMethod();
   }
  
  }

  private myMethod() {
    // Called when this.myValue changes
  }
}
 

И здесь с сеттером.

 
@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {
  private _myValue: any;

  @Input() set myValue(value: any) {
    this._myValue = any;
    this.myMethod();
  }
  
  get myValue(): any {
    return this._myValue;
  }

  constructor() {}

  private myMethod() {
    // Called when this.myValue changes
  }
}