在Angular component中,我试图创建一个新的input html元素,并将其插入模板的特定位置

组件代码

@ViewChild('pickerLocation', { static: false }) pLocationSpan: ElementRef<HTMLSpanElement>;

construc到r(
    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);
  }

Angular相关问答推荐

iOS Mobile Safari - HTML5视频覆盖一切

RXJS运算符用于combineLatest,不含空值

添加@ nx/webpack插件 destruct 了Nativescript构建

如何在Angular中执行一个操作条件为多个可观测值?

Angular 类型的表单不能分配给分部类型

如何使用ANGLING HTTP.POST并将类型更改为键入的回复?

当在server.ts文件中定义API路径时,Angular 17构建失败

显示用户名-Angular

应该显示在表格中的嵌套循环

Angular 从 13.3.8 恢复到 13.3.7

Angular ngFor 索引从 1 开始 循环

Angular CLI 自定义 webpack 配置

Angular 2:无法绑定到 x,因为它不是已知的本机属性

如何在 Angular CLI 1.1.1 版中将路由模块添加到现有模块?

ngx-toastr,Toast 未在 Angular 7 中显示

移除 Angular 组件创建的宿主 HTML 元素 Select 器

在Angular 6 中找不到 HammerJS

为什么 *ngIf 不适用于 ng-template?

模拟子组件 - Angular 2

如果不判断 {{object.field}} 是否存在则出错