javascript - 删除特定项目(索引)方法

标签 javascript angular

因此,我有一个电话列表,我向其中添加了新的输入行,并且为每一行设置了删除方法。

这是模板:

 <div formArrayName="mobiles">
    <div *ngFor="let mobile of mobiles.controls; let i = index" [formGroupName]="i">
        <div class="d-flex align-items-center" [class.pt-4]="i > 0">
            <input class="input" type="text" formControlName="phone">
            <a class="input-remove ml-3">
                <i class="icon icon-trash h3 text-primary" (click)="removeMobile()"></i>
            </a>
        </div>
    </div>
</div>

这些是我在相应组件中的方法:

get mobiles(): FormArray {
    return this.form.get("mobiles") as FormArray;
}

get stations(): FormArray {
    return this.form.get("stations") as FormArray;
}

addMobile() {
    this.mobiles.push(this.fb.group(new PhoneFormGroup()));
}

addStation() {
    this.stations.push(this.fb.group(new PhoneFormGroup()));
}

removeMobile(index: number) {
    this.mobiles.removeAt(index);
    if (this.mobiles.controls.length == 0) {
        this.addMobile();
    }
}

removeStation(index: number) {
    this.stations.removeAt(index);
    if (this.mobiles.controls.length == 0) {
        this.addStation();
    }
}

这里的问题是,每当我单击删除按钮时,它都会从列表中删除第一个项目(索引[0]),而我希望它删除我选择删除的特定项目。

我做错了什么?

最佳答案

您没有将 index 参数从 HTML 模板传递给 removeMobile 函数。

<i class="icon icon-trash h3 text-primary" (click)="removeMobile(i)"></i>

关于javascript - 删除特定项目(索引)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638689/

相关文章:

javascript - 在 Angular 中关闭严格模式?

javascript - d3.js 链接强度对力图中的链接距离的影响

angular - 在 Angular 2 中访问 FormControl

javascript - 为什么 Javascript ES6 中没有定义 `i` ?

javascript - 每次点击重复 div Angular

Angular 2 在 Sublime Text 3 中有错误

javascript - SailsJS - Angular2 - 资源丰富的 Pub/Sub

javascript - Angular 2 : Bind form context to ngTemplateOutlet

javascript - 复选框以显示更多选项

javascript - 在文本区域内显示 div