Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 2 - Custom mat-option/md-option template in autocomplete

Does Angular Material 2 have a selector to customize autocomplete options like Angular Material md-item-template for AngularJS? I couldn't find anything on the docs from Material 2

AngularJS example from the docs:

<md-autocomplete
    <md-item-template>
      <span class="item-title">
        <md-icon md-svg-icon="img/icons/octicon-repo.svg"></md-icon>
        <span> {{item.name}} </span>
      </span>
      <span class="item-metadata">
        <span class="item-metastat">
          <strong>{{item.watchers}}</strong> watchers
        </span>
        <span class="item-metastat">
          <strong>{{item.forks}}</strong> forks
        </span>
      </span>
    </md-item-template>
</md-autocomplete>

enter image description here

like image 975
Rafael Avatar asked Oct 02 '17 17:10

Rafael


3 Answers

Here is what I did to have a multiline option in mat-autocomplete.
For me, the key was to wrap the mat-option content in a div and set display to inline-block.
Maybe someone find it useful.

Template

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let item of filteredItems" [value]="item">
    <div class="multiline-option">
      {{ item.lineOne }} <br />
      {{ item.lineTwo }}
    </div>
  </mat-option>
</mat-autocomplete>

Style

.multiline-option {
  display: inline-block;
  line-height: normal;
}
like image 92
Lars Avatar answered Oct 02 '22 23:10

Lars


The solution for two line mat-autocomplete with picture

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
        <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="20" />
        <span>{{ state.name }}</span> <br>
        <small>Population: {{state.population}}</small>
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
// CSS
.mat-option {
  height: 50px;
  line-height: 20px;
}
like image 8
Ali Altun Avatar answered Nov 13 '22 00:11

Ali Altun


I am also searching for the right way to do it like good 'ol Material 1. This is ugly hack I could get it to work in Material 5:

Style:

.mat-option {
  height: 50px;
  line-height: 20px;
}

Template:

<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
    <!-- <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" /> -->
        <span>{{ state.name }}</span><br>
        <small>Population: {{state.population}}</small>         
    </mat-option>
</mat-autocomplete>

Try it here

like image 5
hbthanki Avatar answered Nov 13 '22 01:11

hbthanki