【发布时间】:2020-10-21 10:17:07
【问题描述】:
我有一个简单的反应式表单,我使用 FormArray 添加/删除项目列表。每个列表项都有一个分配给它的删除按钮,因此我可以从列表中删除该项目。还有一个添加按钮,我可以使用它在列表中添加项目(如下面的源代码所示。Stackblitz link)
import { Component } from "@angular/core";
import { FormArray, FormBuilder, FormGroup } from "@angular/forms";
interface Recipient {
name: string;
email: string;
}
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
form = this.fb.group({
recipients: this.fb.array([])
});
recipient: Recipient = {
name: "",
email: ""
};
constructor(private fb: FormBuilder) {
this.recipients().push(
this.newRecipientGroup({
name: "test",
email: "test email"
})
);
this.recipients().push(
this.newRecipientGroup({
name: "test",
email: "test email"
})
);
}
recipients() {
return this.form.get("recipients") as FormArray;
}
newRecipientGroup(recipient: Recipient) {
return this.fb.group({
name: recipient.name,
email: recipient.email
});
}
addRecipient() {
this.recipients().push(this.newRecipientGroup(this.recipient));
this.recipient = {
name: "",
email: ""
};
}
removeRecipient(i: number, recipient: FormGroup) {
console.log("removeRecipient ->", i, recipient);
this.recipients().removeAt(i);
}
}
<form [formGroup]="form">
<table formArrayName="recipients">
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
</tr>
<tr *ngFor="let recipient of recipients().controls; let i = index;" [formGroupName]="i">
<td>
<input formControlName="name" type="text">
</td>
<td>
<input formControlName="email" type="text">
</td>
<td>
<button (click)="removeRecipient(i, recipient)">Remove
</button>
</td>
</tr>
<tr>
<td>
<input [(ngModel)]="recipient.name" [ngModelOptions]="{standalone: true}" placeholder="Name" type="text">
</td>
<td>
<input [(ngModel)]="recipient.email" [ngModelOptions]="{standalone: true}" placeholder="Email" type="text">
</td>
<td>
<button (click)="addRecipient()" >Add
</button>
</td>
</tr>
</table>
</form>
问题是当我想使用回车键而不是单击添加按钮来添加新列表项时。这样做会调用removeRecipient 方法而不是addRecipient 方法。如果列表中没有项目,则按预期调用addRecipient 方法
为什么会出现这种行为,如何解决?
【问题讨论】:
标签: angular angular-reactive-forms