1

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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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'."
did you try same what I provided in the above stackblitz url?
yes, i have used exactly the same code, but using this link, 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'.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.