yodellingbutters
yodellingbutters

Reputation: 345

How to Close Mat-select Panel when Mouse is out of the box?

Requirement is straight forward but somehow I think I am missing basic concept on the usage of mat-select APIs, I have also followed few Answers but none seems to work.

Requirement: As soon as I take the mouse away from the panel I should be able to click on the Search button.

Current Behavior:

  1. I have to make two clicks on to close the Panel
  2. Another to click on Search button.

Note: The Search button is always Enabled.

enter image description here

Code for the above Mat-select in the image:

<div class="form-group">
     <mat-form-field class="full-width" >
         <mat-select   placeholder="Account Status"  
                       name="statusSelect"
                       #statusSelect="ngModel"
                       [(ngModel)]="advanceSearchFormData.statusSelect" 
                       multiple>
 <mat-select-trigger *ngIf="advanceSearchFormData.statusSelect?.length > 1" >
           Multiple
 </mat-select-trigger>
  <mat-option  *ngFor="let status of accountStatus" 
       [value]="status.accountStatus">
                  {{ status.accountStatus }}
   </mat-option>
   </mat-select>
   </mat-form-field>
   </div>

Upvotes: 1

Views: 9518

Answers (2)

Petar Ivanov
Petar Ivanov

Reputation: 91

I found a clear solution for this case:

   <mat-select #matmat placeholder="observers" [formControl]="observers"
                                [(value)]="selectedViewers" multiple> 
                                <div (mouseleave)="matmat.close()">
                                    <mat-option *ngFor="let user of allUsers" [value]="user">{{user.firstName}}
                                    </mat-option>
                                </div>
     </mat-select>

Upvotes: 3

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Thankfully, MatSelect provides a reference to the panel element, so when it is open, you can grab it and just add event listener to listen mouseleave event:

this.matSelect.openedChange.subscribe(opened => {
  if (opened) {
    this.matSelect.panel.nativeElement.addEventListener('mouseleave', () => {
      this.matSelect.close();
    })
  }
})

And don't forget to remove event listener and unsubscribe.

DEMO

Upvotes: 3

Related Questions