gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:32:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com