4

I have a custom input component, just a cover for regular html input tag. Here is a usage example:

  <form [formGroup]="formGroup">
    <my-input [title]="Some title" formControlName="name"></my-input>
  </form>

And related component contains:

  formGroup: FormGroup = new FormGroup({
    name: new FormControl('', Validators.required),
  });

I managed to access FormControl instance from within my-input component using this approach, now what I want to do, is to add an asterisk to my-input title if it is required.

The question is - is it possible to access list of validators so I can distinguish required validator among them?

P.S. Surely I can put required attribute on the element itself

<my-input ... required></my-input>

But I want use reactive forms.

Majesty
  • 2,097
  • 5
  • 24
  • 55

2 Answers2

4

There is the same issue open in github for a while now (so it seems you are mostly out of luck).

https://github.com/angular/angular/issues/13461

You can see solutions like the one below (thanks mtinner from github) but there is nothing official

  export const hasRequiredField = (abstractControl: AbstractControl): boolean => {
    if (abstractControl.validator) {
        const validator = abstractControl.validator({}as AbstractControl);
        if (validator && validator.required) {
            return true;
        }
    }
    if (abstractControl['controls']) {
        for (const controlName in abstractControl['controls']) {
            if (abstractControl['controls'][controlName]) {
                if (hasRequiredField(abstractControl['controls'][controlName])) {
                    return true;
                }
            }
        }
    }
    return false;
};

You'll see that most people try to solve the same problem as you.

Hope this helps!

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
-1

You can do like this

<span "formGroup.controls['name'].errors?.required>*</span>
  • This will hide the asterisk if a user put something in the input, this is not an expected behaviour and bad practice in terms of UX. Thanks for the suggestion though. – Majesty Oct 24 '19 at 09:36