Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

angular - Form control not working when set custom validation on the form group

This is my group -

this.fb.group( {email: new FormControl('')},
      {
        validators: [ formGroup =>  {email:"some error"}]
      }
    );

this is my form:

<form [formGroup]="formGroup">
  <app-input [control]="loginFormGroup.controls.email"></app-input>
</form>

app input component:

  <input
    matInput
    [formControl]="control"
    [errorStateMatcher]="matcher"
  />

export class MyErrorStateMatcher implements ErrorStateMatcher {
  error = '';
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    if (control?.errors) {
      this.error = control.errors[0];
    }
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

isErrorState always return null, because the control form is always valid. the errors exists only on the form group. what i missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to set validator in FormControl.

this.fb.group({email: new FormControl('', {
  validators: [
    control => {
      return {email: 'some error'};
    }]
  })
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...