2

How can you focus on element inside ngIf?

This ngIf is true when the page loads but it still gets an undefined error:

@ViewChild("currentDaySpentInput") currentDaySpentInput: ElementRef;  
// ...
<div class="spending-input" *ngIf="!spentInputComplete">
    <label>How much did you spend today?</label>
    <input [(ngModel)]="currentDay.spent" (keyup)="onKey($event)" #currentDaySpentInput>
</div>

focus element

ngOnOnit() {
    this.currentDaySpentInput.nativeElement.focus();
}

Error:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

I tried using the setter suggested in this question but it didn't work.

matt
  • 659
  • 2
  • 8
  • 15

2 Answers2

3

ViewChild is available after AfterViewInit hook and not on Onit that's why you are getting the error. (https://alligator.io/angular/viewchild-access-component/)

@ViewChild("currentDaySpentInput") currentDaySpentInput: ElementRef; 
  ngAfterViewInit() {
    console.log(this.currentDaySpentInput.nativeElement.focus()); // mayo
  }

It should fix this issue if this doesn't fix the issue will have to see the code.

Akshay Rajput
  • 1,978
  • 1
  • 12
  • 22
0

The reason you got undefined at startup because the template is not yet rendered and your ViewChild cannot detect its attachment to view

To solve it use AfterViewInit in here your @ViewChild will be resolved, and put your checking in the override method

export class YourComponent implements AfterViewInit {
   @ViewChild() currentDaySpentInput: any;
   ngAfterViewInit(): void {
    // put your logic here
    console.log(this.currentDaySpentInput.nativeElement);
  }
}
John Velasquez
  • 3,421
  • 2
  • 18
  • 23