How to get an Element Reference from the Template Reference which is passed as an Input to a Angular Component

958 views Asked by At

I need to capture the Input Element Reference in an Angular Component.

We usually use @ViewChild (refer element from template) or @ContentChild (refer element from content injected)

In my case, I pass a Template Reference as an @Input to an Angular Component.

@Component({
  selector: "app-test",
  template: `
    <h1>Test component rendering Custom Template Ref passed as input</h1>

    <ng-container [ngTemplateOutlet]="customTemplateRef"></ng-container>
    <br /><br />
    <button (click)="printRef()">Log Input Ref in Console</button>
  `,
  styleUrls: ["./test.component.css"]
})
export class TestComponent {
  @Input() customTemplateRef: TemplateRef<any>;
  @ViewChild("inputRef", { static: false }) inputRef: ElementRef<
    HTMLInputElement
  >;

  printRef() {
    console.log("this.inputRef");
    console.log(this.inputRef);
  }
}
...
...

// template which passed from parent component is
<ng-template #customTemplateRef>
  <input type="text" placeholder="Sample Text Box" #inputRef />
</ng-template>

How I can access the Input Element Reference in the TestComponent ?

I need this in a scenerio to focus that input element when User Clicks anywhere in the TestComponent.

I tried ViewChild, ContentChild nothing is successful :(

My code is in https://stackblitz.com/edit/to-get-element-ref-from-custom-template-ref?file=src/app/test/test.component.ts

Kindly help in resolving it. Thank you.

0

There are 0 answers