如何突出显示默认验证器消息?

How to Highlight and Display Default Validator Message?

这个 StackBlitz,我想学习如何:

  1. 突出显示输入框并将*必填设为红色
  2. 验证器失败时显示一条默认错误消息minLength(4)

您可以将此样式添加到 styles.css

.has-error {
  border: 1px solid red;
}

然后像这样输入:

<input type="text" formControlName="uname"  placeholder="Enter Name..." [ngClass]="{ 'has-error': myForm.controls?.uname.errors && (myForm.controls?.uname.dirty || myForm.controls?.uname.touched) }">

Demo

Jeb,你在定义 FormGroup 时出现类型错误,看看如果我们有两个或更多验证器你传递一个验证器数组

this.myForm = this.fb.group({
  uname: ['', [Validators.required, Validators.minLength(4)]] //<--is an array
});

关于 class 我们可以在 styles.css 中有一些像

input.ng-invalid.ng-touched {   //<--is necesary the "input", else a custom form
                                //control will be bordered too
  border: 1px solid red;
}

如果我们只想在“提交”时使用,例如

input.ng-invalid.ng-touched.submitted {
  border: 1px solid red;
}

并在我们的 ts

中使用一个变量
submitted :boolean=false;

并且我们的输入添加[class.submitted]

<input [class.submitted]="submitted" type="text" formControlName="uname" ..>  

关于中继器有几种方法。一个可以创建一个自定义错误,一个像

这样的组件
@Component({
  selector: 'custom-error',
  template: `
    <small class="error" *ngIf="isInvalid" >
       <ng-content></ng-content>
    </small>
`,
styles:[`
.error{
  color:red
}
`]
})
export class ErrorComponent {
  @Input() submitted:boolean=true;
  get isInvalid() {
    const control = this.form.form.get(this.controlName);
    return this.submitted && control.touched && control.invalid && (this.error ? control.errors[this.error] : true);
  }
  constructor(@Optional() @Host() private form: FormGroupDirective,
    @Attribute("controlName") private controlName,
    @Attribute("error") private error) { }
}

允许我们写一些像

//if we want not wait to submitted and a unique Validators
<custom-error controlName="uname" >Required</custom-error>

//if there're an unique Validators
<custom-error [submitted]="submitted" controlName="uname" >Required</custom-error>

//if we severals validators
<custom-error [submitted]="submitted" error="required" controlName="uname" >Required</custom-error>

我们可以想象另一种只显示一个错误的“自定义错误”

//this "defaultErrors should be in a external file and completed with other erros
//this allow us reemplace case we want "localize" our app

export const defaultErrors = {
  required: (error) => `This field is required`,
  minlength: ({ requiredLength, actualLength }) => `Expect ${requiredLength} but got ${actualLength}`,
  default:'field invalid' //<--add a string with the default error
}

@Component({
  selector: 'custom-error-unique',
  template: `
    <small class="error" *ngIf="hasError" >
       {{hasError}}
    </small>
`,
styles:[`
.error{
  color:red
}
`]
})
export class ErrorUniqueComponent {
   errors=defaultErrors
   @Input() submitted:boolean=true;
   @Input('errors') set _(value)
   {
       this.errors={...defaultErrors,...value}
   }

  @Input() submitted:boolean=true;
  @Input() errors:any=defaultErrors;

  get hasError() {
    const control = this.form.form.get(this.controlName);
    const invalid=this.submitted && control.touched && control.invalid
    let error=null
    if (invalid)
    {
       Object.keys(this.errors).forEach(x=>{
          if (control.errors[x] && !error)
          {
            error=this.errors[x](control.errors[x])
          }
       })
       if (!error)
            error=this.defaultErrors.default

    }
    return  error
  }
  constructor(@Optional() @Host() private form: FormGroupDirective,
    @Attribute("controlName") private controlName,
    @Attribute("error") private error) { }

}

this stackblitz 中有两个自定义错误组件

甚至我们都可以想象它神奇地出现了。好吧,Netanel Basal 在我们面前考虑一下:见 this great entry blog