如果单击“角向提交”时未选中,则显示单选框的验证错误

问题描述 投票:0回答:1

在此示例中,如果单击提交按钮且未选择性别,则希望获得提示“ Angabe eines Geschlechtes ist erforderlich”。我如何通过按钮来达到这个目的?我以为可以在按下“提交按钮”时更改单选按钮的“触摸”状态,但这仅适用于反应式表单,对吗?我有点困惑如何在按下“提交”按钮时触发nfIf错误以显示提示。

<form name="form" #f="ngForm" (ngSubmit)="f.form.valid && onSubmit()">
<div class="col-md-12">
  <div class="form-group col-md-4">
    <label class="btn btn-outline-primary" (click)="toggleActiveStatus($event)">
      <input class="radio-button" type="radio" name="selectedBy" id="female" [(ngModel)]="patient.gender"
             autocoplete="off" value="female" checked #selectedBy="ngModel" required> Weiblich
    </label>
    <label class="btn btn-outline-primary" (click)="toggleActiveStatus($event)">
      <input class="radio-button" type="radio" name="selectedBy" id="male" [(ngModel)]="patient.gender"
             autocomplete="off" value="male" checked #selectedBy="ngModel" required> Männlich
    </label>
    <div class="alert alert-warning" *ngIf="selectedBy.errors?.required && (selectedBy.dirty || selectedBy.touched)">Die Angabe eines Geschlechts ist erforderlich.
    </div>
  </div>

</div>
<button (click)="onSubmit()" type="submit" class="btn btn-primary">Weiter</button>

感谢您的帮助。

angular validation angular-forms angular-formbuilder
1个回答
1
投票

我对使用模板驱动的表单不是很熟悉,并且可能有更好的方法来执行此操作。我确实进行了一次堆叠闪电战,产生了您想要的结果。

基本上,您将使用@ViewChild()来获取ts备份文件中的模板表单。您将具有boolean属性,以确定是否已提交表单。然后,您可以切换该布尔值并在onSubmit()中检查表单的有效性。

app.component.ts

export class AppComponent  {
  @ViewChild("f", { static: false })
  public form;

  public hasFormBeenSubmitted: boolean = false;
  public patient = {
    gender: ''
  }

  public onSubmit() {
    this.hasFormBeenSubmitted = true;

    // check for form validity
    if (this.form.invalid) {
      return;
    }

    console.log(this.patient);
  }
}

然后您可以在模板中提交表单后立即调用onSubmit()。您将在窗体控制警报消息中使用boolean检查*ngIf值和所需的错误。

app.component.html

<form name="form" #f="ngForm" (ngSubmit)="onSubmit()">
  <div class="col-md-12">
    <div class="form-group col-md-4">
      <label class="btn btn-outline-primary">
        <input class="radio-button" type="radio" name="selectedBy" id="female" [(ngModel)]="patient.gender"
              autocoplete="off" value="female" checked #selectedBy="ngModel" required> Weiblich
      </label>
      <label class="btn btn-outline-primary">
        <input class="radio-button" type="radio" name="selectedBy" id="male" [(ngModel)]="patient.gender"
              autocomplete="off" value="male" checked #selectedBy="ngModel" required> Männlich
      </label>
      <div class="alert alert-warning" *ngIf="selectedBy.errors?.required && hasFormBeenSubmitted">Die Angabe eines Geschlechts ist erforderlich.
      </div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Weiter</button>
</form>

https://stackblitz.com/edit/angular-padcsk

© www.soinside.com 2019 - 2024. All rights reserved.