我正在开发一个将下拉列表转换为 radioListbox 的 Angular Directive(指令)。 这是我的初始代码:
import { Directive, Input, TemplateRef, ViewContainerRef,OnInit } from '@angular/core';
@Directive({
selector: '[radioList]'
})
export class RadioListDirective implements OnInit {
constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) {
}
ngOnInit() {
console.log(this.templateRef);
this.vcRef.createEmbeddedView(this.templateRef);
}
}
和
<div>
test
</div>
<select *radioList><option>1</option><option>2</option></select>
它应该记录 TemplateRef
,其 ElementRef
的 nativeElement 是一个 select
。但结果是空注释,它的下一个元素是 select
。
最佳答案
目前有效的 Hacky 解决方案:
捕获下一个兄弟:
this.templateRef.elementRef.nativeElement.nextSibling
使用viewContainerRef.get
(this.viewContainerRef.get(0) as any).rootNodes[0]
(请注意,在您的示例代码中,您使用了 vcRef
而不是我在此处使用的 viewContainerRef
。)
关于angular templateRef nativeElement 是空注释而不是原始元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228535/