Home > front end >  How to get validation errors in custom form control component
How to get validation errors in custom form control component

Time:04-22

I want to make a reusable input. The problem is that I don't know how to pass Validation.errors to a new component from an external component. The problem is also the status of FormControl - it is always valid. I attach the link to the stackblitz. I marked in red the part that I don't know how to solve.

https://stackblitz.com/edit/angular-ivy-evbk9q?file=src/app/app.component.html

CodePudding user response:

You can define parameter for your component as:

<app-custom-input
    [isValid]="formGroup.get('input')?.valid"
    formControlName="input">
</app-custom-input>

and in your component:

@Input() isValid : boolean;

So isValid prop contains info about form input is valid or not.

CodePudding user response:

You need take account that you has two FormControl: the FormControl that you create in app.component -who is the FormControl that has the error- and the "inner" FormControl -the formControl that you use as auxiliar in your custom-input.component

So you need "get" the FormControl in app.component from your custom -input.

You can get the "ngControl" of your control. There're three ways

1.-inject in constructor Inject and in ngOnInit of your custom-input to have some like

ngControl:NgControl
constructor(injector: Injector) {
    this.ngControl = injector.get(NgControl);
    ....rest of your code..
}
ngOnInit()
{
    this.ngControl = injector.get(NgControl);
}

2.- Remove the two providers and inject directly the ngControl -but you loose the "validation"

  constructor(public ngControl: NgControl) {
      if (!!ngControl) {
        ngControl.valueAccessor = this;
      }
      ...
  }

So we can use

<div style="color: red;">
  value: {{ ngControl.control.value | json }}
  <br />
  errors: {{ ngControl.control.errors | json }}
  <br />
 valid:  {{ ngControl.control.valid | json }}
</div>

3.- The third way is, as we have a validate function, we can get the control (not the ngControl) in this function

  control:FormControl=null

  validate(control: FormControl) {
    if (!this.control)
      this.control=control
    return this.formControl.valid ? null : { profile: { valid: false } };
  }

And we can write

<div style="color: red;">
  value: {{ control.value | json }}
  <br />
  errors: {{ control.errors | json }}
  <br />
 valid:  {{ control.valid | json }}
</div>
  • Related