Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep autocomplete suggestion panel open for multiple selection and close when clicked outside of panel in angular material 2

Tags:

angular

I want to modify the autocomplete component for multiple selection. What I want is that the suggestion panel should be opened for multiple selection via checkbox, and close it if user clicks outside of suggestion panel. As per the docs we can handle it via panelClosingActions but I cant find any way how to use it.

M able to keep Panel open via MdAutocompleteTrigger event and openPanel method but what happens is if 2nd index is selected and m selecting 4th index then 2nd index checkbox unticks and ticks again.

<md-autocomplete #auto="mdAutocomplete" id=autoComplete>
  <md-option *ngFor="let state of filteredStates | async" 
[value]="state.name" (click)="handleAutocomplete()">
<md-checkbox [checked]="state.selected" [(ngModel)]="state.selected">
    <span>{{ state.name }}</span> |
    <small>Population: {{state.population}}</small>
</md-checkbox>
  </md-option>
</md-autocomplete>

@ViewChild('autocomplete', {read: MdAutoCompleteTrigger})
autoComplete: MdAutocompleteTrigger

handleAutocomplete(){
this.autoComplete.openPanel();
}

Any help is really appreciated

like image 606
Rohan Sampat Avatar asked Sep 25 '17 07:09

Rohan Sampat


1 Answers

I'm facing the same issue.

Only solution I found is to immediately reopen the options panel when an option is selected using mat-autocomplete optionSelected method.

HTML

<mat-autocomplete 
#auto="matAutocomplete" 
[displayWith]="displayFn" 
(optionSelected)="openPanel()">
    <mat-option *ngFor="let tag of filteredSources" [value]="tag.id">
        <span>{{ tag.text }}</span>
    </mat-option>
</mat-autocomplete>

TS

@ViewChild(MatAutocompleteTrigger) autoTrigger: MatAutocompleteTrigger;
openPanel(): void {
    const self = this;
    setTimeout(function () {
        self.autoTrigger.openPanel();
    }, 1);
}

This is not an elegant solution as the panel still closes and there is a blinking effect, but I couldn't find a better solution as MatAutocompleteTrigger panelClosingActions is readonly.

like image 166
Roketz Avatar answered Sep 18 '22 15:09

Roketz