Angular 函数更改值后视图不更新
我有一个删除标签的函数,可以添加到一个数组中,从另一个数组中删除。此零件工作正常,但当更新新值时,视图不会更新:Angular 函数更改值后视图不更新,angular,Angular,我有一个删除标签的函数,可以添加到一个数组中,从另一个数组中删除。此零件工作正常,但当更新新值时,视图不会更新: accountDelete(id, name) { let accountsToAdd = this.userForm.value.accountsToAdd; const accountsToDelete = this.userForm.value.accountsToDelete; accountsToDelete.push( {
accountDelete(id, name) {
let accountsToAdd = this.userForm.value.accountsToAdd;
const accountsToDelete = this.userForm.value.accountsToDelete;
accountsToDelete.push(
{
id: id,
name: name
}
);
console.log(accountsToDelete);
accountsToAdd = accountsToAdd.filter(account => account.id !== id);
console.log(accountsToAdd);
}
模板为:
<div class="tag-wrapper mt-3">
<span class="badge tag" *ngFor="let account of userForm.value.accountsToAdd">
<span class="tag-title">{{ account.name }}</span>
<button class="btn btn-secondary btn-sm" (click)="accountDelete(account.id, account.name)">
<span class="fa fa-times"></span>
</button>
</span>
</div>
您正在将结果携带到accountDelete方法内的变量,并且必须携带到范围
accountDelete(id, name) {
this.userForm.value.accountsToDelete.push(
{
id: id,
name: name
}
);
console.log(this.userForm.value.accountsToDelete);
this.userForm.value.accountsToAdd = this.userForm.value.accountsToAdd.filter(account => account.id !== id);
console.log(this.userForm.value.accountsToAdd);
}这很有效,谢谢。我想我明白这一点。因此,由于变量是在函数中定义的,因此它们的值仅限于该函数的范围。因此,我必须将值重新分配给类范围?
accountDelete(id, name) {
this.userForm.value.accountsToDelete.push(
{
id: id,
name: name
}
);
console.log(this.userForm.value.accountsToDelete);
this.userForm.value.accountsToAdd = this.userForm.value.accountsToAdd.filter(account => account.id !== id);
console.log(this.userForm.value.accountsToAdd);