将formControl标记为已验证/已检查?

时间:2019-07-19 06:53:12

标签: angular

当输入无效但仅在提交表单之后,我想在输入字段下方显示错误消息。

我可以简单地使用布尔值,并在表单提交后立即对其进行切换,并将其作为显示消息的条件,但是我不能在我的应用程序中这样做,因为它有点复杂。

提交反应形式时,我将每个控件标记为已触摸,并在* ngIf中将错误布尔值作为条件来提示错误提示。

Object.keys(selectForm.controls).forEach(key => {
   selectForm.get(key).updateValueAndValidity();
   if(!selectForm.get(key).valid) {
     selectForm.get(key).markAsTouched();
   } 
})

此解决方案无法完美运行,因为当用户仅“触摸”输入时,错误提示文本也会弹出。

<form [formGroup]="selectForm">
    <p-dropdown [options]="items" formControlName="selected" placeholder="Select" (onChange)="save()"></p-dropdown>
    <p-message *ngIf="selected.invalid && selected.errors.required && selected.touched" severity="error" text="Field is required"></p-message>
</form>

基本上,我正在寻找类似nestedForm.get(key).markAsChecked()的东西  但这不存在。

这里的解决方案是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用errorMessageBindingStrategy中的@rxweb/reactive-form-validators来实现。

您只需要像这样在app.component.ts中设置"errorMessageBindingStrategy":1

 ngOnInit(){
    //if you want to apply global configuration then use below code. 
    ReactiveFormConfig.set({
      "validationMessage":{
        "required":"This field is required"
        },
        "reactiveForm":{
          "errorMessageBindingStrategy":1
        }});
  }

并在您要通过其显示错误消息的Submit方法上将submitted的{​​{1}}属性设置为true:

RxFormGroup

完整的组件代码

 OnSubmit() {
    this.selectForm.submitted = true;
  }

完整的HTML代码

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder } from "@angular/forms"
import { RxFormBuilder, RxFormGroup, RxwebValidators } from '@rxweb/reactive-form-validators';


@Component({
  selector: 'app-errormessagestrategy-onsubmit-validator',
  templateUrl: './errormessagestrategy-onsubmit.component.html'
})
export class ErrormessagestrategyOnsubmitValidatorComponent implements OnInit {
  selectForm: RxFormGroup

  constructor(
    private formBuilder: RxFormBuilder, private fb: FormBuilder) { }

  ngOnInit() {
    this.selectForm = <RxFormGroup>this.formBuilder.group({
      userName: ['', RxwebValidators.required()],
      password: ['', RxwebValidators.required()],
      address: this.formBuilder.group({
        city: ['', RxwebValidators.required()]
      })
    });

  }

  OnSubmit() {
    this.selectForm.submitted = true;
  }


}

Working Example