多个提交按钮,呈角度2形式

2022-08-20 00:00:00 javascript angular angular2-forms

我正在构建angular2表单,我希望有多个按钮来提交表单,例如"保存"和"保存并关闭"。

我已尝试使用带有单击操作的简单按钮,但我找不到手动将表单标记为已提交以强制表单验证的方法。

<form #ticketForm="ngForm" novalidate>
    <input type="text" id="customerName" required
        name="customerName" [(ngModel)]="ticket.customerName"
        #customerName="ngModel">

    <div class="tj-form-input-errors"
        *ngIf="customerName.errors && (customerName.dirty ||
        customerName.touched || ticketForm.submitted)">

        <small [hidden]="!customerName.errors.required">
            Customer name is required
        </small>
    </div>

    <button type="button" (click)="save(ticketForm)">Save</button>
    <button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>

解决方案

为每个按钮分配不同的id。然后您可以使用document.activeElement.id获取触发提交的按钮的id。如下所示:

在您的HTML中:

<form #form="ngForm" (submit)="firstSave(form,$event)">
    ...
    <div class="form-group">
        <input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
        <input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
    </div>
</form>

然后在您的打字稿中:

firstSave(form: NgForm, $event: Event) {
  var activeButton = document.activeElement.id;
  if (activeButton == "submit-1") {
    alert("you have clicked on submit 1");
  }
  if (activeButton == "submit-2") {
    alert("you have clicked on submit 2");
  }
}

StackBlitz Here.

相关文章