Topic: How to autofocus on dynamic modal's form control

galileo priority asked 1 year ago


Expected behavior When opening a modal window containing a form through modalService I want a default form field control (textArea) to be focused, but adding autofocus to textArea tag doesn't work. I've also followed this outdated tutorial and it didn't work:

https://mdbootstrap.com/support/angular/how-to-set-focus-on-input-in-modal/

Actual behavior Nothing happens (form field is not focused)

Resources (screenshots, code snippets etc.)



Please try to add a delay by wrapping your code in setTimeout function. Here is an example code that you can use in your modal component ts file (in this case you need to add #input template variable to the HTML element you want to focus):

  @ViewChild('input', { static: true }) input: ElementRef<HTMLInputElement>;

  constructor(public modalRef: MDBModalRef) {}

  ngOnInit() {
    setTimeout(() => {
      this.input.nativeElement.focus();
    }, 0);
  }

galileo priority commented 1 year ago

It worked! Thank you :)



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Angular
  • MDB Version: MDB4 12.0.0
  • Device: laptop
  • Browser: Chrome
  • OS: Win
  • Provided sample code: No
  • Provided link: Yes