arrays - 根据选择删除存储在数组中的项目
问题描述
我正在尝试根据所选选项删除存储在数组中的项目,以更好地理解阅读此代码:
component.html
<fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto">
<fnd-option *ngFor="let p of agreementfilter?.landingPageTypes" [value]="p.id">{{p.description}}</fnd-option>
</fnd-extended-select>
Component.ts
deleteMsg() {
this.agreementfilter.landingPageTypes.splice(1, 1);
}
基本上使用此代码时,当我按下按钮删除项目时,仅删除数组的第一个对象。
我需要什么:删除我从数组中选择的项目。
我有什么样的选择来解决这个问题?
谢谢您的帮助!
解决方案
组件.html
<fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType"
name="tipoprodotto">
<fnd-option *ngFor="let p of agreementfilter?.landingPageTypes; let i = index"
[value]="i">{{p.description}}</fnd-option></fnd-extended-select> <button (click)="deleteMsg(landingType)"></button>
组件.ts
landingType;
public deleteMsg(id: number) {
// finds index of item to be deleted and then deletes the item from the array
this.landingPageTypes.splice(id, 1);
// output array to console with item deleted
console.log('landingPageTypes: ', this.landingPageTypes);
}
public change(id) {
// change select and index store in variable
this.landingType = id;
console.log(id);
}
查看示例stackblitz