Ans
Ans

Reputation: 147

setTimeout() not working properly, How to get focus in input field?

I want to achieve focus on input when the pop-up modal loads

HTML

<custom-input #name id="name" formControlName="name"
      ngDefaultControl  maxlength="3" minlength="2">
</custom-input>

popup-modal.component.ts

  @ViewChild('name', { static: true }) name: ElementRef;

parent.component.html

<popup-modal #childComponent" >
</popup-modal>

parent.component.ts

  openPopUp() {

this.popUpChild.popUp.nativeElement.open= true;
 setTimeout(() => {
   this.popUpchild.name.nativeElement.focus();
 }, 0);
}

I tried to open modal pop up from parent and set focus in name input but sometime it is coming sometimes not becuase of setTimeout. How to achieve focus every time in name input field when opens a modal pop up?

Upvotes: 0

Views: 1872

Answers (2)

JWP
JWP

Reputation: 6963

Set your timeout to 100. Ensure the z-order is highest. Focus only works on highest layer.

Also DOM rendering is done at the end of each update cycle. When you put in a small timeout delay, it gives the DOM time to render. Which means all of the view is ready to go. There are other ways but this is easiest.

Z-order brings any element to the top. Very important using material components.

Upvotes: 1

Roman Šim&#237;k
Roman Šim&#237;k

Reputation: 900

The problem is that, when you set the open variable to true, the element is still not rendered in HTML. To do that you need to force Change Detection manually and also you don't need to use setTimeout anymore.

parent.component.ts

constructor(private changeDetectorRef: ChangeDetectorRef) {}

openPopUp() {
    this.popUpChild.popUp.nativeElement.open= true;
    this.changeDetectorRef.detectChanges();
    this.popUpchild.name.nativeElement.focus();
}

Upvotes: 1

Related Questions