【发布时间】:2019-08-17 22:26:39
【问题描述】:
在我的应用程序中,我有一个输入元素,当我单击按钮时它是可见的,当我单击另一个按钮时它是隐藏的。我通过一个简单的 ng-template 实现了这一点。我想在此输入可见时为其设置焦点。我将autofocus 参数设置为输入,但如果我多次切换可见性(输入失去焦点),它就不起作用。我已经尝试了这个SO 问题中描述的替代方案(ViewChild、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;
}
}
工作stackblitz。
【问题讨论】:
标签: angular