How to disable free text in md-autocomplete component of angular material?

How to disable free text in md-autocomplete? I want users to be able to select only from a list of items or add an ng message based on some check if the item is not selected from the list. Angular stuff MD auto-fill demo

+6
source share
2 answers

It is possible, but it requires some workarounds. You basically do a manual check in selectedItemChange and searchTextChange .

 function searchTextChange(text) { self.form.id.$error.stateMissing = true; $log.info('Text changed to ' + text); } function selectedItemChange(item) { $log.info(self.form.id); if (item === null) { $log.info('invalid'); } else { $log.info('valid'); delete self.form.id.$error.stateMissing; self.form.id.$validate(); } } 

The error is set in the stateMissing property, and then used in the ng-message markup. It is important to set the form name so that you can reference the form in your controller.

 <form name="ctrl.form" novalidate> <p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p> <md-autocomplete md-autoselect md-select-on-focus md-floating-label="Select a state" ng-disabled="ctrl.isDisabled" cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-input-name="id" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" md-selected-item-change="ctrl.selectedItemChange(ctrl.selectedItem)"> <md-item-template> <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span> </md-item-template> <md-not-found> No states matching "{{ctrl.searchText}}" were found. <a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a> </md-not-found> <div ng-messages="ctrl.form.id.$error"> <div ng-message="stateMissing">You must select a state</div> </div> </md-autocomplete> 

http://codepen.io/kuhnroyal/pen/eZXXVr

+4
source

You can add new items to the list on the fly:

 <md-autocomplete flex required="required" md-input-name="id" md-selected-item="newItem.item" md-search-text="itemSearch.queryText" md-items="itemin itemSearch.querySearch()" md-item-text="item.name" md-input-minlength="2" md-floating-label="enter here"> <md-item-template> <span md-highlight-text="itemSearch.queryText" md-highlight-flags="^i">{{item.name}}</span> </md-item-template> <md-not-found> Sorry, this is not in our database </md-not-found> <div ng-messages="formName.id.$error"> <div ng-message="required">You must enter a name</div> <div ng-message="minlength">You must type at least two characters</div> </div> </md-autocomplete> 

edit: just enter your message inside <md-not-found>

0
source

All Articles