1

What I'm trying to achieve is automatically set a asterisk on a input when a given control has the validation rule 'required'.

Component ts:

this.form = this.fb.group({
    name: ['', [Validators.required]]
});

Component template:

<label>
    <span>Name</span>
    <input type="text" [appRequiredAsterisk]="form.get('name')" formControlName="name" id="name">
</label>

My Directive:

@Directive({
    selector: '[appRequiredAsterisk]'
})
export class RequiredAsteriskDirective implements OnInit {
    @Input() appRequiredAsterisk: AbstractControl;

    constructor(private el: ElementRef) { }

    ngOnInit(): void {
        // Append Asterisk here..
    }
}

I can't find a way to see if the validation rule 'required' is set on the AbstractControl appRequiredAsterisk. How can I do this?

Mike Bovenlander
  • 5,236
  • 5
  • 28
  • 47

1 Answers1

2

Something like:-

let isRequired = appRequiredAsterisk.errors['required'];

if (isRequired) {
    //show asterix
}

Edit:

Issue with above is that obviously when the error disappears so will the asterix.

Found this here which actually gives you the validators

let nameControlVald = this.form.controls['name'].validator('');
console.log(nameControlVald, "validators");

Looks like this is the best way to solve your issue. So pass in this.form.controls['name'] to the directive and set the above then check if required exists.

Joe Keene
  • 2,175
  • 21
  • 27