March 30th, 2020
12:05 pm
Angular delay reference to *ngIf target until created

Posted under Angular & Web

I had some code which toggled the value checked by an *ngIf, to cause the *ngIf target to be created.

I then wanted, in the same component method immediately afterwards, to refer to the target (which was a ViewChild)  to set focus to it. At that point I got an undefined error, as it had not yet been created and added to the DOM.

This post here details the issue and how to get around it.

Basically, using a setTimeout and setting the focus in its callback solved the problem. The interesting part of the trick detailed in the post was that the timeout could be legitimately set to 0, as all we needed to do was put our callback function on the end of the message queue which would always ensure that Angular change detection runs before the setFocus() call. This worked fine, using the following code:-

// set the state which will trigger the *ngIf to create the focus target
this.autocompleteState = AutocompleteStates.Initial;

// now set the focus as a timeout callback
setTimeout(() => this.searchbar.setFocus(), 0);

 

 

 

Comments Off on Angular delay reference to *ngIf target until created

Comments are closed.