Set focus to an input that is hidden with *ngIf


I am trying to create a dynamic form that hides and shows one input at a time.

I would like to be able to jump to the next input when the ngIf doesnt hide it anymore. So far I have found this directive :

import { Directive, AfterViewInit, ElementRef } from '@angular/core';

  selector: '[directFocus]'
export class AutofocusDirective implements AfterViewInit {

  constructor(private elementRef: ElementRef) { };

  ngAfterViewInit(): void {


But it doesn’t work … Has anyone come past such a problem ?

Thank you,

1 Like

I have a similar problem, I have a search region with a search input and it is hidden or visible according to the condition established in the ngIf.
I can’t use ViewChild , it raise a error.

One idiom I have successfully used in the past when dealing with @ViewChild and elements that aren’t always in the DOM is to use a setter:

slides: Slides;
@ViewChild(Slides) set slidesvc(slides) {
  this.slides = slides;