Home > front end >  How to set Validator to custom form control in Angular
How to set Validator to custom form control in Angular

Time:03-10

<form [formGroup]="fg">
    <custom-control formControlName="custom">
    </custom-control>
</form>
this.fg = this.fb.group({
      custom: [null,Validator.required]
});

This the custom control component:

@Component({
  selector: 'custom-control',
  template: `
        <input [formControl]="inputFormControl" />
        <mat-error *ngIf="inputFormControl.hasError('required')">Required</mat-error>
  `,
  styleUrls: ["custom-control.component.scss"],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi:true,
      useExisting: CustomControlComponent
    }
  ]
})
export class CustomControlComponent implements ControlValueAccessor {

  inputFormControl: new FormControl();
  onChange = (quantity) => {};

  onTouched = () => {};

  writeValue(quantity: number) {
    this.quantity = quantity;
  }

  registerOnChange(onChange: any) {
    this.onChange = onChange;
  }

  registerOnTouched(onTouched: any) {}
}

How can this required error be displayed? and What if I set aother validator through fg.get('custom').setValidator(XXX) ? Thanks

CodePudding user response:

If you want to use mat-error:

  • the mat-error element needs to be in a mat-form-field with the input which is throwing the error
  • the FormControl that is physically in the mat-form-field must be the exact FormControl which is validated

In your current state of affairs, you need to add a mat-form-field around your custom-control and place the mat-error in there with it as opposed to having the mat-error inside custom-component.

CodePudding user response:

implement Validator interface and provide NG_VALIDATORS

 @Component({
  selector: 'custom-control',
  template: `
        <input [formControl]="inputFormControl" />
        <mat-error *ngIf="inputFormControl.hasError('required')">Required</mat-error>
  `,
  styleUrls: ["custom-control.component.scss"],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi:true,
      useExisting: CustomControlComponent
    },
    {
        provide: NG_VALIDATORS,
        useExisting: forwardRef(() => CustomControlComponent),
        multi: true,
    },
  ]
})
export class CustomControlComponent implements ControlValueAccessor, Validator {

  inputFormControl: new FormControl();
  onChange = (quantity) => {};

  onTouched = () => {};

  writeValue(quantity: number) {
    this.quantity = quantity;
  }

  registerOnChange(onChange: any) {
    this.onChange = onChange;
  }

  registerOnTouched(onTouched: any) {}

  onValidatorChange = () => {
  };

  registerOnValidatorChange(fn: () => void): void {
    this.onValidatorChange = fn;
   }

  validate(c: AbstractControl): ValidationErrors | null {
    return this.inputFormControl.invalid ? { internal: true } : null;
  }
}
  • Related