How do we control what field has the focus on a page when first loaded?
I have a page and expected the first field (top left) to automatically get the focus so the user can start typing (text field), but this is not the case.
I tried an autofocus property, but no luck.
There are several ways that you can do this and the right solution depends on the structure of the page. If field you are trying to focus has a native input element inside it, you can add a local name to it (firstInput for example) and use this:
setTimeout(()=>{
this.firstInput.nativeElement.focus()
}
The setTimeout gives the page a chance to render the input element.
If you are using a Dynamic Components Field, then something like this would work better:
setTimeout(async () => {
let element;
while (!element) {
await new Promise((resolve) => setTimeout(resolve, 10));
element = this.firstField.viewContainerRef.element.nativeElement.querySelector('input');
debug('element', element);
element?.click();
}
});
The setTimeout is still there but the logic is extended to wait until the input shows up. Ideally you should have an iteration limit on this loop so that it does not iterate forever if the element does not appear.
for the Dynamic Field component that I was using, this worked well:
setTimeout(async () => {
let element;
let count = 0;
while (!element && count < 1000) {
await new Promise((resolve) => setTimeout(resolve, 10));
element = this.titleField.viewContainerRef.element.nativeElement.querySelector('input');
debug('element', element);
count++;
element?.click();
}
});