In my app I've an input element which is visible when I click on button and hidden, when I click on another button. I realized this with a simple ng-template. I want to set the focus for this input whenever it becomes visible. I set the autofocus
parameter to input, but it doesn't work if I toggle the visibility multiple times (the input lost the focus). I've tried alternatives (ViewChild
, Renderer2
) described in this SO question, but it doesn't work either.
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;
}
}
Working stackblitz.