How to use correctly autocomplete component from A

2019-09-12 02:12发布

问题:

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