angularangular-materialdropdownmat-select

Angular's mat-select is not closing when clicking outside


I am using angular material's select component to load some options to choose from. When I click on the field, the list of options appear as expected, however, when I click anywhere outside the options, the select does not close. I have noticed that this issue is only persistent on mobile phones, even when inspecting on chrome and changing the dimensions to that of a phone the problem still persists.

component.ts:

<mat-form-field>
    <mat-label>City</mat-label>
    <mat-select formControlName="cityId" (valueChange)="onCityChange($event)">
      <mat-option *ngFor="let city of cities" [value]="city.id">
        {{city.name}}
      </mat-option>
    </mat-select>
    <mat-error *ngIf="form.get('cityId').hasError('required')">
        This field is required
    </mat-error>
</mat-form-field>

Solution

  • Please try below approach

      constructor(private renderer: Renderer2) {}
    
    
    
    ngOnInit() {
      this.renderer.listen('document', 'click', (event: MouseEvent) => {
        const targetElement = event.target as HTMLElement;
        const matSelectElement = document.querySelector('.mat-select-panel');
    
        if (matSelectElement && !matSelectElement.contains(targetElement)) {
          // Close the mat-select when clicking outside
          this.matSelect.close();
        }
      });}
    
    
    <mat-select #matSelect formControlName="cityId" (valueChange)="onCityChange($event)">