无法删除 \[object Array\] 的属性“1”

新手上路,请多包涵

在我的组件中获取 Input 列表:

@Input() usersInput: Section[];

 export interface Section {
    displayName: string;
    userId: number;
    title: number;
}

这是值列表:

     0:
     displayName: "بدون نام"
     firstName: null
     lastName: null
     title: 0
     userId: 1
   1:
     displayName: "محمدامین چهاردولی"
     firstName: "محمدامین"
     lastName: "چهاردولی"
     title: 0
     userId: 2

ngAfterViewInit 我将输入值设置为用户列表:

 ngAfterViewInit(): void {
    this.users = this.usersInput;
    if (this.users.length === 0) {
        this.show = false;
    } else {
        this.show = true;
    }
}

这是用户:

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>

现在当我需要使用删除按钮时:

   <button (click)="deleteUser(item.userId)" mat-button>
       <mat-icon aria-label="Delete" color="accent">delete</mat-icon>
  </button>

TS :

     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();
}

它告诉我这个错误:

错误类型错误:无法删除 [object Array] 的属性“1”

有什么问题???我该如何解决?

原文由 kianoush dortaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 237
2 个回答

尝试:

 deleteUser(id) {
    const index = this.users.findIndex(x => x.userId === id);
    this.users.splice(index, 1);
}

工作演示

原文由 Adrita Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

我遇到了同样的问题,根据 这篇文章, 问题是用户数组具有不可配置的属性。我想角度输入设置为不可配置。当您这样做时: this.users = this.usersInput 您只需将输入的引用传递给 this.users 。解决方案是在拼接之前简单地复制输入数组。在你的情况下:

     this.users = [...this.usersInput];

顺便提一句。在 deleteUser 方法中执行此操作,而不是使用局部变量的 afterViewInit。您不需要引用同一对象的两个类道具。

原文由 Rabov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题