How to use correctly autocomplete component from Angular2 MaterialDesign?

♀尐吖头ヾ 提交于 2019-12-12 02:18:33

问题


I have been trying to use the autocomplete component from Angular Material2. But I have some doubts.

  1. How to load suggestion data from HTTP service, and filter this list on the fly?

  2. How to get access to selected option(object) in my component?

  3. Is there any way to formatting selected option with HTML (multiline values), like on PrimeNg autocomplete using pTemplate?

Sample: https://embed.plnkr.co/vR9QLk/


回答1:


You can get the selected item with help of the function, you have your selected item in the object selectedOption

displayFn(state: ExampleDataMode): string {
        this.selectedOption = state;
        console.log(this.selectedOption);///displays the selected item
        return state ? state.name : '';

    }

Also, you can handle the events that are used to select the item from the dropdown and bind them to object as

 <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
      <md-option *ngFor="let state of filteredStates | async" [value]="state" (click)="selectedItem=state">
      {{ state.name }}
      </md-option>
    </md-autocomplete>

and you will have the selected Item in your selectedItem object.

Note: The above handles only if the user clicks on the item, where as it wont work if the user selectes through key events which needs to be handled separately.

LIVE DEMO



来源:https://stackoverflow.com/questions/42879917/how-to-use-correctly-autocomplete-component-from-angular2-materialdesign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!