1

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>

1 Answers1

0

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)">
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 04 '23 at 15:21