kia*_*taj 6 javascript typescript angular
Input在我的组件中获取列表:
@Input() usersInput: Section[];
export interface Section {
displayName: string;
userId: number;
title: number;
}
Run Code Online (Sandbox Code Playgroud)
这是值列表:
0:
displayName: "???? ???"
firstName: null
lastName: null
title: 0
userId: 1
1:
displayName: "???????? ????????"
firstName: "????????"
lastName: "????????"
title: 0
userId: 2
Run Code Online (Sandbox Code Playgroud)
在ngAfterViewInit我将输入值设置为用户列表:
ngAfterViewInit(): void {
this.users = this.usersInput;
if (this.users.length === 0) {
this.show = false;
} else {
this.show = true;
}
}
Run Code Online (Sandbox Code Playgroud)
这是用户:
users: Section[] = [];
我在 html 列表中使用它:
<div *ngFor="let item of users" class="d-flex selected-list-items mt-3">
<div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
<label>{{item.displayName}}</label>
</div>
<div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
<label> {{ getEnumTranslate(item.title)}}</label>
</div>
<div class="justify-content-center col-md-2 col-lg-2 col-xs-2 col-sm-2 col-xl-2">
<button (click)="deleteUser(item.userId)" mat-button>
<mat-icon aria-label="Delete" color="accent">delete</mat-icon>
</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在当我需要使用删除按钮时:
<button (click)="deleteUser(item.userId)" mat-button>
<mat-icon aria-label="Delete" color="accent">delete</mat-icon>
</button>
Run Code Online (Sandbox Code Playgroud)
:
deleteUser(id: number): void {
let userModel = {} as Section;
userModel = this.users.find(x => x.userId === id);
const index = this.users.indexOf(userModel);
this.users.splice(index, 1);
this.emitValueModel.push(
{
title: this.user.title,
userId: this.user.userId
}
);
this.selectedUserId.emit(this.emitValueModel);
if (this.users.length === 0) {
this.show = false;
}
this.cdref.detectChanges();
}
Run Code Online (Sandbox Code Playgroud)
它告诉我这个错误:
错误类型错误:无法删除 [object Array] 的属性“1”
有什么问题???我该如何解决?
小智 7
我遇到了同样的问题,根据这篇文章,问题是用户数组具有不可配置的属性。我想角度输入被设置为不可配置。当您这样做时:
this.users = this.usersInput
您只需将输入的引用传递给this.users. 解决方法是在拼接前简单地复制输入数组。在你的情况下:
this.users = [...this.usersInput];
Run Code Online (Sandbox Code Playgroud)
顺便提一句。在 deleteUser 方法而不是具有局部变量的 afterViewInit 中执行此操作。您不需要引用同一个对象的两个类道具。
我在我的 React 应用程序中遇到了这个问题,但假设同样的问题也发生在 Angular 中。错误的原因是我通过 JS 扩展运算符进行浅复制。
const newArr = [...oldArr];
newArr.splice(1) // Remove all items except for the first one.
// This would throw the error `Cannot delete property '1' of [object Array]`
Run Code Online (Sandbox Code Playgroud)
解决方案是安装 lodash.clonedeep 并执行深度克隆。
import cloneDeep from "lodash.clonedeep";
const newArr = cloneDeep(oldArr);
newArr.splice(1) // Remove all items except for the first one.
// Success!
Run Code Online (Sandbox Code Playgroud)
尝试:
deleteUser(id) {
const index = this.users.findIndex(x => x.userId === id);
this.users.splice(index, 1);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12430 次 |
| 最近记录: |