1

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

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

1st approach works. for more fine grained differentiation between FormControlName and FormControl as result of injector.get(NgControl) please see medium.com/@toha.marko/…
1

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.

1 Comment

the idea is get the formGroup.get('input') from the custom-input, not passing as Input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.