javascript - 如何从作为输入传递给 Angular 组件的模板引用中获取元素引用
问题描述
我需要在 Angular 组件中捕获输入元素引用。
我们通常使用@ViewChild
(refer element from template) 或@ContentChild
(refer element from content injection)
就我而言,我将模板引用作为@Input
Angular 组件传递。
@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
.
我试过了ViewChild
,ContentChild
没有成功:(
请帮助解决它。谢谢你。
解决方案
推荐阅读
- c++ - Go/C++ gRPC 客户端通道和存根生命周期
- spring - JUnit 5 和 Spring Framework 3.2.x
- python - 在 saltstack 中部署 Python 代码
- html - 我网站上悬停激活的 3D 视差效果
- python - Python 导入错误,未找到符号:_iconv 引用自:
- javascript - 对象值未定义:MEAN Stack
- javascript - Javascript:代码重构为单行而不是多行 for 循环
- javascript - 不执行返回 - Javascript,React.js
- android - 如何更改列表数据结构firebase数据库android的值?
- android - 我想从谷歌登录中检索用户信息并将其放在导航侧边栏上