angular templateRef nativeElement - пустой комментарий вместо исходного элемента

Я разрабатываю директиву angular, которая преобразует раскрывающийся список в 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);

  }
}

а также

<div>
  test
</div>


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

Он должен регистрировать TemplateRef, чей nativeElement ElementRef - это select. Но результатом является пустой комментарий, что его следующим элементом является select.

введите описание изображения здесь


person theGhostN    schedule 08.05.2018    source источник
comment
Попробуйте частный шаблонRef: TemplateRef ‹any›   -  person Tiago Machado    schedule 08.05.2018
comment
Я пробовал раньше. Все еще не работает.   -  person theGhostN    schedule 08.05.2018
comment
It should log the TemplateRef whose ElementRef 's nativeElement is a select где вы это прочитали? Работает как задумано   -  person yurzui    schedule 08.05.2018
comment
@yurzui где вы читаете, что это предполагаемое поведение (ссылка на пустой комментарий)?   -  person theGhostN    schedule 09.05.2018
comment
The elementRef that is available on the templateRef as shown here just points to the DOM host element that Angular created for the template element - it's a comment node. stackoverflow.com/a/44940608/5485167   -  person yurzui    schedule 09.05.2018


Ответы (1)


В настоящее время работают хакерские решения:

Возьмите следующего брата и сестру:

this.templateRef.elementRef.nativeElement.nextSibling

Используйте viewContainerRef.get

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

(Обратите внимание, что из вашего примера кода вы использовали vcRef вместо viewContainerRef, как я использовал здесь.)

person electrovir    schedule 21.02.2019