Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mat select click outside not working, when drop down close

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

like image 928
kunal Avatar asked Jun 05 '18 11:06

kunal


People also ask

How do you bind a value in mat select?

Create Select using <mat-select> To add elements to select option, we need to use <mat-option> element. To bind value with <mat-option> , we need to use value property of it. The <mat-select> has also value property to bind selected value to keep it selected. We need to use <mat-select> inside <mat-form-field> element.


1 Answers

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');
}
like image 92
G. Tranter Avatar answered Sep 20 '22 13:09

G. Tranter