单击按钮时的反应式表单验证

Reactive Form Validation on Button Click

我正在尝试验证 Angular 项目中的输入字段并使用教程,它似乎按预期工作。

Validation in Angular

以上使用 Reactive Form 进行如下验证工作:

<form [formGroup]="angForm" novalidate>
    <div class="form-group">
        <label>Name:</label>
        <input class="form-control" formControlName="name" type="text">
    </div>
    <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
    </div>
     <div class="form-group">
        <label>Address:</label>
        <input class="form-control" formControlName="address" type="text">
    </div>
    <div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['address'].errors.required">
          email is required.
        </div>
    </div>
    <button type="submit"
        [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success">
        Save
    </button>
</form>

上面的按钮默认是禁用的。因此,当用户开始书写并将输入字段留空时,它会验证表单。我的要求是启用该按钮,当单击时,验证将起作用。所以我做了如下:

<form [formGroup]="angForm" #addData='ngForm' (ngSubmit)="AddData(addData)">

<button type="submit" class="btn btn-success"> //Removed the disabled property
   Save
</button> 

TypeScript 中做了这个:

AddData(addData: NgForm) {
  this.createForm();
}

createForm() {
  this.angForm = this.fb.group({
    name: ['', Validators.required ]
  });
}

虽然它没有按预期触发验证。所以我想要的是触发我无法在此处执行的按钮单击验证。有什么办法可以解决吗?

也许你可以在你的 AddData 函数上添加一点逻辑:

AddData() {
  if (this.angForm.valid) {
    //Logic for valid form
  } else {
    Object.keys(this.angForm.controls).forEach(field => {
    const control = this.form.get(field);
    control.markAsTouched({ onlySelf: true });
   });
  }
}

这将在用户单击按钮时将元素标记为已触摸,这将触发用于显示错误消息和输入样式的逻辑,假设是:

!this.angForm.controls['name'].valid && this.angForm.controls['name'].touched;