angular - 每次在 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;
}
}
工作堆栈闪电战。
解决方案
根据autofocus 属性的描述,它应该只关注“页面加载”样式功能,而不是创建/删除内容时。
在页面上显示后,您可以使用@ContentChild
with 。this.contentChild.nativeElement.focus()
您还可以订阅QueryList
from@ContentChildren
以触发焦点(在此处找到)。
推荐阅读
- arrays - 有什么方法可以将函数名称从 JSON 数据绑定到 Angular 按钮的(单击)
- python - 用python3中元组列表中的两个元素排序
- azure-databricks - Databricks-CLI - ValueError:超时值连接超时
- spring-boot - Spring Boot @RestClientTest 如何使用真实服务器进行测试(不是模拟)
- kerberos - RAT 标志是什么意思?
- c++ - 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- c# - unity 3d 游戏的移动键盘自定义
- python - 尝试使用 Python 通过 API 访问数据时出错
- asp.net-mvc - Session.Abandon() 之后 TempData 不工作
- spring - 结合 Spring 规范和 PostgreSQL 进行模糊匹配