Angular directive query sibling HTML

196 Views Asked by At

Using Angular 10 I want to query a sibling element. Essentially I have something like this:

<label myDirective for="foo" ...
<input id="foo" formControlName="xyz" ...

In myDirective I can easily get the value of for via a @HostBinding. In my directive I then want to get the formControlName of the element with the given ID. I'm not sure how to do that because it seems like my directive might run before the input element has been created, for example.

I'm trying to automate a bit so I don't have to write this:

<label [myDirective]="foo.attributes.getNamedItem('formControlName').value" ...
<html #foo ...
1

There are 1 best solutions below

2
On BEST ANSWER

You can create an @Input() inside your directive code. Your directive:

  @Input() for;

  ngOnChanges() {
    if (!!this.for) {
      console.log(this.for.attributes.formcontrolname.nodeValue); // name
    }
  }

Your HTML code:

<form [formGroup]="form">
  <div appDirective [for]="any"> 
  <input #any formControlName="name">
  </div>
</form>

That way you have the formControlName attribute you asked for. To get its value, I don't see a way not inputing the form too. Or you can access the this.for.value. But you must be careful because this will take the native element input value.