material-web icon indicating copy to clipboard operation
material-web copied to clipboard

unable to listen to clicks on textfield icon (trailing and leading)

Open christophe-g opened this issue 3 years ago • 3 comments

Describe the bug

It is not possible to listen to a click event on a textfield icon as this style is being applied on icons :

.mdc-text-field__icon:not([tabindex]), .mdc-text-field__icon[tabindex="-1"] {
    cursor: default;
    pointer-events: none;
}

Expected behavior

Listenting to a click event should be able to tell if an icon was clicked

<mwc-textfield label=label trailingIcon=delete @click=${this.onDelete}></mwc-textfield>
 onDelete(e) {
  const clickedElement = e.composedPath()[0]; 
}

Workaround Extend textfield and override the above style or renderIcon method to add tabindex=0 to the icon.

christophe-g avatar May 25 '21 18:05 christophe-g

How about multiple action icons? Couldn't think of other alternative than slot

yinonov avatar Aug 10 '21 04:08 yinonov

What is the (current) recommended way to handle events on icon-buttons in text-fields? I am trying to implement a password field with a trailing "eye" icon to toggle masking/unmasking the password.

exhuma avatar Jan 26 '22 13:01 exhuma

For what it's worth, this is the mixin I use to override textfield :

import { html } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
/**
 * mixin overriding how mdc-textfiel handle icons
 *
 *
 * Related issue:
 * https://github.com/material-components/material-components-web-components/issues/2447
 *
 */

export const OverrideTextfielIcon = (baseElement) => class extends baseElement {
  renderIcon(icon, isTrailingIcon) {
    const classes = {
      'mdc-text-field__icon--leading': !isTrailingIcon,
      'mdc-text-field__icon--trailing': isTrailingIcon
    };

    return html`<i class="material-icons mdc-text-field__icon ${classMap(classes)}" tabindex="0">${icon}</i>`;
  }
};

export default OverrideTextfielIcon;

christophe-g avatar Jan 26 '22 21:01 christophe-g

Obsolete now that icons are slotted with M3

asyncLiz avatar Aug 02 '23 02:08 asyncLiz