Renderer2.appendChild没有按预期工作?



在Angular组件中,我试图创建一个新的inputhtml元素并插入到模板的特定位置

组件代码

@ViewChild('pickerLocation', { static: false }) pLocationSpan: ElementRef<HTMLSpanElement>;
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
@Inject(DOCUMENT) private document: Document) { }
ngOnInit(): void {
const pickerInput = this.renderer.createElement('INPUT');
const picker = new TempusDominus(pickerInput);
this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);
}

模板代码

<div class="col-sm-6">
<label for="datetimepickerInput">{{label}}</label>
<span id="locationSpan" ngModel #pickerLocation></span>
<span class="input-group-text">
<span class="fa-solid fa-calendar"></span>
</span>
</div>

但是如果我改变

this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);

this.renderer.appendChild(this.elementRef.nativeElement, pickerInput);

可以工作,但是我需要在特定位置输入。那么问题是什么呢?

@ViewChild查询元素只可能在NgAfterViewInit()生命周期最早。因为<span #pickerLocation>需要在被查询和访问之前先渲染。

ngAfterViewInit(): void {
const pickerInput = this.renderer.createElement('INPUT');
const picker = new TempusDominus(pickerInput);
this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);
}

最新更新