[英]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.在 Angular 中,我想将父(App 组件)推送到现有数组中的子组件绑定数据。 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.我想将“数据”推送到“deletedToDo”数组中,以便我可以在 ngFor 模块中使用 deletedToDo 数组。
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.最初第一个控制台是空白的,在 push 方法第二个数组获取数据之后,但是在下一个活动中,当一个更多的已删除数据出现在这种情况下,而不是在数组中添加数据时,它被替换。 length of array is still-1
数组的长度仍然是-1
Expectation- data should be added in deletedTodo array every time when delete button is clicked through which input is coming in delData.预期-每次单击删除按钮时,数据都应添加到 deletedTodo 数组中,输入将通过该按钮进入 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;您遇到的问题是每次向其传递新数据时都会调用
set delData(data: todeModel[])
setter function; 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.并且,每次调用它时,它都会创建
deletedTodo
数组的一个新实例,并且只将数据数组的第一个元素添加到其中。
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.要解决此问题,您应该在 setter function 之外初始化
deletedTodo
数组,使其仅创建一次,然后使用展开运算符 ( ...
) 将数据数组的所有元素添加到其中。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.