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

问题描述 投票:2回答:1

我正在开发一个将dropdownlist转换为radioListbox的angular指令。这是我的初始代码:

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的nativeElement是ElementRefselect。但结果是空的评论,其下一个元素是select

enter image description here

angular angular5 directive elementref
1个回答
0
投票

Hacky解决方案目前有效:

抓住下一个兄弟姐妹:

this.templateRef.elementRef.nativeElement.nextSibling

使用viewContainerRef.get

(this.viewContainerRef.get(0) as any).rootNodes[0]

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

© www.soinside.com 2019 - 2024. All rights reserved.