首页 > 解决方案 > 如何从作为输入传递给 Angular 组件的模板引用中获取元素引用

问题描述

我需要在 Angular 组件中捕获输入元素引用。

我们通常使用@ViewChild(refer element from template) 或@ContentChild(refer element from content injection)

就我而言,我将模板引用作为@InputAngular 组件传递。

@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>

如何访问 ? 中的输入元素参考TestComponent

当用户单击TestComponent.

我试过了ViewChildContentChild没有成功:(

我的代码在https://stackblitz.com/edit/to-get-element-ref-from-custom-template-ref?file=src/app/test/test.component.ts

请帮助解决它。谢谢你。

标签: javascriptangulartypescriptviewchild

解决方案


推荐阅读