How to getting a reference to elements within the container of an angular structural directive

291 Views Asked by At

I have the following template with a test structural directive called *appUnless:

<h1 *appUnless>
  <app-hello></app-hello>
  <input type="text" value="hello" />
</h1>

Inside of my structural directive, so far I have this:

import {
  Directive,
  Input,
  TemplateRef,
  ViewContainerRef,
} from "@angular/core";

@Directive({
  selector: "[appUnless]",
})
export class UnlessDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input()
  set appUnless(message: string) {
    const embeddedViewRef = this.viewContainer.createEmbeddedView(
      this.templateRef
    );
  }
}

How do I get a reference to the input element from within the directive? I want to be able to refer to the input no different than if I had placed a template reference declaration on it, i.e., if I were to do <input #myInput>. Obviously, since I don't control the contents of what is placed inside of the container, I can't place #myInput into the template.

Also, how do I get a reference to the AppHelloComponent (one that backs app-hello) with correct type from within this directive?

0

There are 0 best solutions below