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

标签 angular angular5 directive elementref

我正在开发一个将下拉列表转换为 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

enter image description here

最佳答案

目前有效的 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/

相关文章:

Angular 2 : Get Authorization header

css - 在 Angular Material 表中使用省略号

javascript - Angular4加载JS文件的方法

javascript - 无法正确使用元素指令

angularjs - 如何手动编译模板两次或多次

angular - Phantomjs 在 Jenkins 上崩溃 : Auto configuration failed

wordpress - 如何整合WooCommerce和Angular 2

Angular 4 动态表单 - 如果未触及则为空值 - 如何获取这些显示的默认值?

javascript - Angular:显示文本区域内的文本区域字符数

javascript - 在 Angular 指令链接中向 div 添加 onclick 函数