Search code examples
angularcomponentsstate

Angular component state like React use state hook


I came to Angular from React experience .

In react I use the Use State hook or set State in classes for example to handle component state .so if state changes the component re renders to reflect changes

I ended up making a parent child components and passes @input to the child and in the child I used ngOnChange

And this done the trick

But what is the standard and simplest way to do it instead of adding a parent extra component since no job for the parent component except passing @input to do this trick


Solution

  • There are multiple ways by which I do this, 2 of which are -

    1. Using getter and setter for the variable.
    export class MyComponent {
    
     private _myProp: any;
    
     public get myProp(): any {
       return this._myPorp;
     }
    
     public set myProp(val: any) {
       this._myProp = val;
       // enter code here which you want to execute on property value change.
     }
    
     constructor () {
       // notice that I am using myProp and not _myProp
       this.myProp = 'some arbitrary value';
     }
    }
    
    1. Using rxjs Subject - link
    import { Subject } from 'rxjs';
    
    ...
    export class MyComponent implements OnInit {
     myPropSubject = new Subject();
    
     constructor() {
       this.myPropSubject.subscribe((val) => {
         // enter code here which you want to execute on property value change.
       });
     }
    
     ngOnInit(): void {
       this.myPropSubject.next('some arbitrary value');
     }
    }