angular templateRef nativeElement is an empty comment instead of original element

一世执手 提交于 2020-05-29 03:56:06

问题


I am developing an angular directive that converts dropdownlist to radioListbox. here is my initial code :

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

  }
}

and

<div>
  test
</div>


<select *radioList><option>1</option><option>2</option></select>

It should log the TemplateRef whose ElementRef 's nativeElement is a select. But the result is and empty comment that its next element is the select .


回答1:


Hacky solutions currently working:

Grab the next sibling:

this.templateRef.elementRef.nativeElement.nextSibling

Use viewContainerRef.get

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

(Note, from your example code you used vcRef instead of viewContainerRef as I used here.)



来源:https://stackoverflow.com/questions/50228535/angular-templateref-nativeelement-is-an-empty-comment-instead-of-original-elemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!