Focus an element after it appears via ngIf Focus an element after it appears via ngIf typescript typescript

Focus an element after it appears via ngIf


You can use ViewChildren and the QueryList.changes event to be notified when the button is added to or removed from the view. If the QueryList contains the button element, you can set the focus on it. See this stackblitz for a demo. Suggestion: you may want to do something similar to set the focus on the input field when it becomes visible.

import { Component, ViewChildren, ElementRef, AfterViewInit, QueryList } from '@angular/core';...export class AppComponent implements AfterViewInit {  @ViewChildren("durationButton") durationButton: QueryList<ElementRef>;  enteringDuration = false  ngAfterViewInit() {    this.setFocus(); // If the button is already present...    this.durationButton.changes.subscribe(() => {      this.setFocus();    });  }  setFocus() {    if (this.durationButton.length > 0) {      this.durationButton.first.nativeElement.focus();    }  }  enterDuration() {    this.enteringDuration = true  }  setDuration() {    this.enteringDuration = false  }}


Yes, *ngIf and ViewChild don't play well together. I did a course on ViewChild and did an entire section just on handing the *ngIf.

One option is to use the hidden attribute instead of *ngIf.

Another option is to bind to a setter (similar to how you bound to a function):

enter image description here