Mat select click outside not working, when drop down close
Asked Answered
A

1

8

I have drop down made with Mat select angular component, I need to trigger an event when I clicked outside of the drop down (body of the page).

<mat-select #select multiple (change)="onSubmit($event)" [(ngModel)]="emp">
    <mat-option *ngFor="let value of filter.default" [value]="value">
        {{value}}
    </mat-option>
</mat-select>

Here is my ts file

export class AnotherComponent {
  public text: String;

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      console.log("clicked inside");
    } else {
      console.log("clicked outside");
    }
  }

  constructor(private eRef: ElementRef) {

  }
}

Its not working properly, please help

Anglophobia answered 5/6, 2018 at 11:11 Comment(5)
what do u mean not working properly?Parotid
if I click on open drop down options, its also showing "clicked outside" in console, it should display only if drop down close, please adviseAnglophobia
use if(!this.eRef.nativeElement.contains(event.target))Parotid
If I click to open the drop down it also shows "clicked outside" in console.Anglophobia
Any way to exclude particular elementAnglophobia
S
20

If you want to know when the select panel is closed, use the openedChange event:

<mat-select #select multiple (change)="onSubmit($event)" [(ngModel)]="emp"
    (openedChange)="openedChange($event)">
    <mat-option *ngFor="let value of filter.default" [value]="value">
        {{value}}
    </mat-option>
</mat-select>


openedChange(opened: boolean) {
    console.log(opened ? 'opened' : 'closed');
}
Studley answered 5/6, 2018 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.