0

I have add buttons at two separate places inside my component. On click of the button, the input field shows up. I have tried multiple ways to achieve this as follows:

Used autofocus attribute on the input field - as i have two buttons on the screen, autofocus does not seem to work.

Used .focus() method -

HTML File

<button (click) = "addUser()">Add User</button>

<input *ngIf="showInputField" #userName />

TS File

@ViewChild('userName') userName:ElementRef;
addUser() { this.showInputField=true; this.userName.nativeElement.focus(); }

In second case, i got the error "cannot read the property nativeElement of undefined", which is because the HTML loads after the execution of method completes.

kirti
  • 47
  • 1
  • 9

2 Answers2

2

You can implement AfterViewChecked in your component and then just remove that this.userName.nativeElement.focus() in addUser() method.

addUser() { 
  this.showInputField = true; 
}

ngAfterViewChecked(): void {
  if (this.showInputField) {
    this.userName.nativeElement.focus();
  }
}

Reference: https://stackblitz.com/edit/angular-ycuvth?file=src/app/autocomplete-auto-active-first-option-example.ts

  • Thanks for quick reply, the solution seems to work, but i am getting an error in the console after using this lifecycle hook "Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'mat-form-field-should-float': 'false'. Current value: 'true'." – kirti Nov 17 '20 at 10:40
  • did you try same what I provided in the above stackblitz url? – Arunkumar Ramasamy Nov 17 '20 at 10:55
  • yes, i have used exactly the same code, but using this [link](https://github.com/angular/components/issues/12070), i got rid of the above error, post which i am getting ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'mat-focused': 'false'. Current value: 'true'. – kirti Nov 17 '20 at 12:14
0

It's probably not the best solution but you can use setTimeout() to wait for the boolean value to change.

addUser() {
  this.showInputField = true;
  setTimeout(() => this.userName.nativeElement.focus());
}

Seen here : https://stackoverflow.com/a/50014475/6444705

Emilien
  • 2,701
  • 4
  • 15
  • 25