在表单提交后应用错误类并显示错误字段的相关验证消息?角2

问题描述 投票:3回答:2

我的表单提交功能目前看起来像这样:

submitListing(value: string): void {
    if(this.newListingForm.valid) {
      console.log("Form Valid");
    } else {
      console.log("Form Invalid");
    }
  }

在这里,我检查我的整个表单是否有效,如果没有(else条件)我想将.error类应用于此表单中的所有无效字段并显示相关的错误消息。我能够在表单上关注this guide并了解如何在用户在表单中输入数据时实现此目的,但是如何在提交表单后执行此操作?

以下是表单中的示例部分:

<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">

<input type="text" placeholder="New Title" [(ngModel)]="mainTitleInput" [ngFormControl]="newListingForm.find('mainTitleInput')" id="main-title_input" class="transparent">

<!-- etc.. -->

</form>

和我的app.ts中的相关验证代码(使用FormBuilder)

//New Listing Form
this.newListingForm = fb.group({
  'mainTitleInput': ['', Validators.compose([Validators.required])]
});
angular forms typescript validation
2个回答
1
投票

只需在您的班级中设置一个字段,并将其包含在您用于显示错误指示符(*ngIf="!newListingForm.controls['mainTitleInput'].valid && isSubmitted)的条件中。

var isSubmitted: boolean = false;

submitListing(value: string): void {
  this.isSubmitted = true;
  if(this.newListingForm.valid) {
    console.log("Form Valid");
  } else {
    console.log("Form Invalid");
  }
}

1
投票

要完成Günter的答案,您还可以利用ngClass指令添加一些类来显示错误。例如,使用Twitter Bootstrap,它将是has-error类:

<form [ngFormModel]="companyForm">
  (...)
  <div class="form-group form-group-sm"
       [ngClass]="{'has-error':!companyForm.controls.name.valid}">
    <label for="for" class="col-sm-3 control-label">Name</label>

    <div class="col-sm-8">
      <input [ngFormControl]="companyForm.controls.name"
             [(ngModel)]="company.name"/>
      <span *ngIf="!companyForm.controls.name.valid"
            class="help-block text-danger">
        <span *ngIf="companyForm.controls.name?.errors?.required">
          The field is required
        </span>
      </span>
    </div>
  </div>

希望它对你有帮助,蒂埃里

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