Search code examples
reactjsangularlifecycle

Does Angular have lifecycle same as React lifecycle useEffect with dependency? And what is it and example?


I have trouble with angular lifecycle

For example, I want to do some actions when a specific state/property is changed

React code example:

const [isChanged, setIsChanged] = useState(false);

useEffect(() => {
     // do some actions I expect here
}, [isChanged]);

How to change the code above into Angular code. Thank you a lot!


Solution

  • Angular has the OnChanges interface, which provides the ngOnChanges lifecycle method.

    Here's the example from the official documentation:

    @Component({selector: 'my-cmp', template: `...`})
    class MyComponent implements OnChanges {
      @Input() prop: number = 0;
    
      ngOnChanges(changes: SimpleChanges) {
        // changes.prop contains the old and the new value...
      }
    }
    

    This is a catch-all for all property changes.

    If you just want to do something when one particular property changes, it might be "cleaner" to just use a setter for the property, and invoke your desired behavior there, for example:

    @Component({selector: 'my-cmp', template: `...`})
    class MyComponent implements OnChanges {
      _prop: number = 0;
      @Input() set prop(value: number) {
        const oldValue = this._prop;
        this._prop = value;
        this.onPropChange(oldValue, this._prop);
      }
    
      get prop(): number {
        return this._prop;
      }
    
      onPropChange(oldValue: number, newValue: number) {
      }
    }