Reputation: 5426
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?
Upvotes: 1
Views: 1150
Reputation: 2351
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.
Upvotes: 2