0

As https://github.com/angular/material/issues/2727 tells it's not possible to use a floating label and the default clearbutton functionality of angular material together. So what's a clean way to achieve such a behavior, by using a directive?

braX
  • 11,506
  • 5
  • 20
  • 33
Niklas Zantner
  • 182
  • 2
  • 16

1 Answers1

0

HTML

<md-autocomplete md-floating-label="LABEL"
                 md-selected-item="$ctrl.model" md-search-text="$ctrl.searchText"
                 md-selected-item-change="$ctrl.itemChanged($ctrl.model)"
                 md-items="item in $ctrl.items" clear-autocomplete
                 md-autoselect="true" required>
  /* whatever you need, e.g. <md-item-template> or <md-not-found> tags */
</md-autocomplete>

None of the $ctrl attributes has to be named the way they are here, just call them whatever you like.

DIRECTIVE

angular
  .module('yourModule')
  .directive('clearAutocomplete', clearAutocomplete);

function clearAutocomplete($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      const button = angular.element('<md-button>').addClass('clear-autocomplete');
      button.append('<i class="material-icons">clear</i>');
      element.append(button);

      let searchTextModel = $parse(attrs.mdSearchText);

      scope.$watch(searchTextModel, function(searchText) {
        if (searchText && searchText !== '' && searchText !== null) {
          button.addClass('visible');
        } else {
          button.removeClass('visible');
        }
      });

      button.on('click', function() {
        searchTextModel.assign(scope, undefined);
      });
    }
  }
}

CSS (that's of course optional)

.em-clear-autocomplete {
  position: absolute;
  transform: translate(0, -100%);
  right: 8px;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.25s linear;

  &.visible {
    visibility: visible;
    opacity: 1;
    cursor: pointer;
  }

  i {
    font-size: 20px;
  }
}

If you use pre ES16, just replace let and const by var. If you have problems understanding the $parse, have a look at the official docu: https://docs.angularjs.org/api/ng/service/$parse

Huge thanks to @sebastianhenneberg !

Niklas Zantner
  • 182
  • 2
  • 16