首页 > 解决方案 > 每次在 ng-template 中设置输入焦点

问题描述

在我的应用程序中,我有一个输入元素,当我点击按钮时它是可见的,当我点击另一个按钮时它是隐藏的。我通过一个简单的 ng-template 实现了这一点。我想在此输入可见时为其设置焦点。我将autofocus参数设置为输入,但如果我多次切换可见性(输入失去焦点),它就不起作用。我已经尝试过这个SOViewChild question 中描述的替代方案( , ) ,但它也不起作用。Renderer2

app.component.html

<div *ngIf="!isInputVisible; else inputTemplate">Input goes here after click!</div>

<button (click)="toggleInputVisibility()">Toggle input</button>

<ng-template #inputTemplate>
  <input type="text" autofocus>
</ng-template>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public isInputVisible: boolean = false;

  public toggleInputVisibility(): void {
    this.isInputVisible = !this.isInputVisible;
  }
}

工作堆栈闪电战

标签: angular

解决方案


根据autofocus 属性的描述,它应该只关注“页面加载”样式功能,而不是创建/删除内容时。

在页面上显示后,您可以使用@ContentChildwith 。this.contentChild.nativeElement.focus()

您还可以订阅QueryListfrom@ContentChildren以触发焦点(在此处找到)。


推荐阅读