Home > Software engineering >  How to update the input decorator value in angular 14
How to update the input decorator value in angular 14

Time:07-15

Trying to change the input array value. But not working in angular 14.I do not know why it is not working. If anyone knows please help to find the solutions.

app.component.ts:

changeVal() {
      this.httpClient.get<string[]>('assets/role.json').subscribe((data) => {
      this.allData = data;
      console.log(data);
      });
   }

Demo: https://stackblitz.com/edit/angular-ivy-3p6bxk?file=src/app/auto/auto.component.ts

CodePudding user response:

This why there's an ngOnChanges() life cycle hook!

When the value from parent changes, the child would have no idea about it, therefor, we use OnChanges interface, and implement the ngOnChanges() method that accepts a SimpleChanges param, in which it get called whenever the value is changed at parent side.

Here's and edited stackblitz that is working.

Happy coding.

CodePudding user response:

Actually, your code is doing what it supposed to do :)
In your auto.component.ts your are reading and assigning to the rateData only during the component initialization. This mean that the next changes to your @Input() data will just stay there and will not be assigned to your rateData property.

The simplest solution would be to use a setter.
Something like this

  @Input() set data (data: Array<string>) {
    this.rateData = data;
  }
  • Related