【发布时间】:2017-05-09 00:25:42
【问题描述】:
使用结构指令,我如何获得指令所在的(本机)元素? 使用普通指令,ElementRef 有它的 nativeElement 指向它 - 例如:
<input type="text" example>
@Directive({
selector: '[example]'
})
export class ExampleDirective {
constructor( private el: ElementRef) {}
ngAfterViewInit() {
console.log(this.el.nativeElement); // the input
}
}
但是使用结构指令,它指向模板注释 - 例如。
<input type="text" *example>
@Directive({
selector: '[example]'
})
export class ExampleDirective {
constructor(
private el: ElementRef,
private view: ViewContainerRef,
private template: TemplateRef<any>
) {}
ngAfterViewInit() {
this.view.createEmbeddedView(this.template);
console.log(this.el.nativeElement); // template bindings comment
// how to find the input itself?
}
}
我尝试过使用 ViewContainerRef、TemplateRef、@ContentChild、@ViewChild 的各种组合 - 只是似乎无法找到输入元素本身...
【问题讨论】:
-
在另一个问题中考虑这个答案stackoverflow.com/a/57796556/2145997
标签: angular