按下回车键时,带有添加/删除按钮的FormArray以奇怪的顺序激活



我有一个简单的反应表单,我使用FormArray添加/删除项目列表。每个列表项都分配了一个"删除"按钮,这样我就可以从列表中删除该项。还有一个添加按钮,我可以用来添加列表中的项目(如下源代码所示。Stacklitz链接(

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方法

为什么会出现这样的行为?如何解决?

我认为在您的代码中;删除收件人";功能,您需要定义按钮的类型。在表单中,按钮的作用类似于";提交";默认情况下,但如果你像下面这样定义按钮的类型,那么它将不会提交你的表单,也不会调用"删除收件人";功能。

<button (click)="removeRecipient(i, recipient)" type="button">Remove</button>

我试过你给定的代码,它对我有效。

最新更新