angular templateRef nativeElement 是一个空注释而不是原始元素

use*_*286 6 directive angular elementref angular5

我正在开发一个角度指令,将下拉列表转换为 radioListbox。这是我的初始代码:

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);

  }
}
Run Code Online (Sandbox Code Playgroud)

<div>
  test
</div>


<select *radioList><option>1</option><option>2</option></select>
Run Code Online (Sandbox Code Playgroud)

它应该记录TemplateRefElementRefnativeElement 是 a 的select。但结果是它的下一个元素是select.

在此处输入图片说明

ele*_*vir 5

目前有效的 Hacky 解决方案:

抓住下一个兄弟姐妹:

this.templateRef.elementRef.nativeElement.nextSibling
Run Code Online (Sandbox Code Playgroud)

使用 viewContainerRef.get

(this.viewContainerRef.get(0) as any).rootNodes[0]
Run Code Online (Sandbox Code Playgroud)

(注意,从您使用的示例代码vcRef而不是viewContainerRef我在这里使用的示例代码中。)