Power Web Design
Power Web Design

Reputation: 139

How to use correctly autocomplete component from Angular2 MaterialDesign?

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/

Upvotes: 0

Views: 1253

Answers (1)

Aravind
Aravind

Reputation: 41533

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

Upvotes: 1

Related Questions