1

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.

Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

2 Answers2

0

Based on the description of the autofocus attribute, it should only focus on "page load" style functionality, not when content is created/removed.

You can use @ContentChild with this.contentChild.nativeElement.focus() after it's shown on the page.

You could also subscribe to a QueryList from @ContentChildren to trigger the focus (found here).

0

May be this might help if you are still looking for a solution. I have used @ViewChild decorator to get he input element and set the focus on it. I am using a delay here to make it async. You may use detect changes as well.

Modified your stackblitz.

Rajesh Panda
  • 636
  • 6
  • 10