material-components / material-web

Material Design Web Components
https://material-web.dev
Apache License 2.0
8.79k stars 827 forks source link

md-*-text-field focus() does not work #5621

Closed shadow-identity closed 2 weeks ago

shadow-identity commented 2 weeks ago

What is affected?

Accessibility, Component

Description

.focus() method called on md-*-text-field instance returns undefined, but does not do anything.

Reproduction

Lit.dev repro

Workaround

Would be great to know how it can be worked around

Is this a regression?

No or unsure. This never worked, or I haven't tried before.

Affected versions

1.4.1

Browser/OS/Node environment

Tested on Firefox 127.0b2 (64-bit) and Chrome Version 124.0.6367.207 (Official Build) (x86_64)

asyncLiz commented 2 weeks ago

It looks like you're calling textField.focus() too early before the custom element is upgraded by the browser. Try waiting for customElements.whenDefined() and textField.updateComplete before focusing.

reportFocus();

customElements.whenDefined('md-filled-text-field').then(async() => {
  await textField.updateComplete;
  textField.focus();
  reportFocus();
});

After the lit.dev playground loads, press the refresh button (focusing in iframes is a bit weird) https://lit.dev/playground/#gist=977b358fe1b2176685160bd2c4b7bf08

Let us know if that helps!

shadow-identity commented 2 weeks ago

That seems to be working, thanks!