Home > Software design >  How to pass response updated data from parent to child component in angular 14
How to pass response updated data from parent to child component in angular 14

Time:07-13

Trying to pass the response data from parent to child component. I have used input decorator. But, it is not working. Previous values are only shown. So, How we can show the updated array response data. If anyone knows please help to find the solution.

app.component.ts:

  public allData = ['Van1', 'Hills2', 'Root3'];
  constructor(private dataService: DataService) {}

  ngOnInit(): void {
      this.dataService.getData().subscribe((data) => {
      this.allData = data;
      console.log(this.allData); // It is data.json data
  });
  }

Demo : enter image description here

CodePudding user response:

If you want to pass data betweeen components , you should use to @Input @Output decorators. those decorators must be in the child component.

CodePudding user response:

The problem is onInit is ran once and before data updates. Whats happenning is:

  1. parent oninit triggers the data fetch
  2. child is created, onInit(where you were assigning the data) runs but data is empty
  3. data comes back in the parent then passed to the child
  4. Missing part: assign the data after the update

What you need is a setter to your input like that: Stackblitz

detail component:

  _data: any = [];
  @Input() set data(array: any) {
    this._data = array;
    this.allInfo = array;
  };

  get data(): any {
    return this._data
  };
  • Related