简体   繁体   中英

how to push parent to child bounded data in existing array of child component in Angular?

In Angular, I want to push parent(App component) to child component bounded data in an existing array. let me show by code what I want--

export class DeletedToDoComponent{
  deletedTodo: todeModel[] = [];

  @Input() set delData(data:todeModel[]){
    console.log("deletedTodo before push", this.deletedTodo);
    this.deletedTodo.push(data[0]);
    console.log("deletedTodo after push", this.deletedTodo);
  }

}

I want to push "data" in "deletedToDo" array so that I can use deletedToDo array in ngFor module.

Issue in this code-

initially 1st console is blank, after push method 2nd array getting data but on next activity when one more deleted data is coming in that case instead of adding data in array it is replaced. length of array is still-1

Expectation- data should be added in deletedTodo array every time when delete button is clicked through which input is coming in delData.

The issue you're encountering is that the set delData(data: todeModel[]) setter function is being called every time new data is passed to it; and, each time it is called, it is creating a new instance of the deletedTodo array and only adding the first element of the data array to it.

To fix this, you should initialize the deletedTodo array outside of the setter function so that it is only created once, and then use the spread operator ( ... ) to add all elements of the data array to it.

export class DeletedToDoComponent {
  deletedTodo: todeModel[] = []; // initialize the array here

  @Input() set delData(data: todeModel[]) {
    console.log("deletedTodo before push", this.deletedTodo);
    this.deletedTodo.push(...data); // use the spread operator to add all elements of the data array
    console.log("deletedTodo after push", this.deletedTodo);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM