-2

I have prepared a directive that should be set on each formControl that is checking if given formControl contains a required validator. More or less based on this: Angular FormControl check if required but wrapped into directive.

Now I am stuck on problem of finding closest label element to add special class to it. I started with getting this.el.nativeElement.previousSibling and appending class via renderer2 but then I noticed that not every input in my app is the same and I have 2 cases possible:

<div>
  <label></label>
  <input directive></input>
</div>

or

<div>
  <label></label>
  <div>
    <input directive></input>
    <span></span>
  </div>
</div>

How to get closest label to my input? Tried using webAPI's closest function but it seems not working and returning null unless I am calling it on wrong object (tried both - this.el and this.el.nativeElement).

Or is my apprach totally wrong and it should be done somehow else?

Chaki
  • 73
  • 6
  • What exactly do you want to achieve with this? I do believe there are other solutions. – MoxxiManagarm Jul 16 '19 at 14:01
  • Basically I want to mark all required fields by making the labels of required fields bolder than non required ones. Also while at this I wanted to refresh my memory about directives and DOM manipulation – Chaki Jul 16 '19 at 14:09

1 Answers1

2

A better approach would be adding an ngClass attribute to your label whenever the control has an error (or even a particular one).

<form [formGroup]="form">
  <label [ngClass]="{ 'field-error': form.controls.myinput.errors }">
  <input formControlName="myinput">
</form>

Hope this helps!

EDIT: based on your requirements you can check for required errors in your form control

<label [ngClass]="{ 'field-error': form.controls.myinput.errors?.required }">

EDIT2:

<label [ngClass]="{ 'field-required': hasRequiredValidator(form.controls.myinput) }">

and in your component:
hasRequiredValidator(control => /* return true if control has Validators.required */);

G-Host
  • 356
  • 2
  • 11
  • Hey, thanks for the answer but this will work only when the field contains an error. I want to mark fields (making the label bolder) that are required. No matter if it is already filled (no error) or still empty – Chaki Jul 16 '19 at 14:12
  • the error attribute is available since the form is instantiated and you should see the class applied as soon as you load the page. Try it – G-Host Jul 16 '19 at 14:18