How to prevent opening details when clicking on mat-label?

27 Views Asked by At

I have multiple details elements. When clicking on mat-label, details is opening, whether $event.stopPropagation() is used or not. I would like to prevent that behaviour because the user expects to focus the input instead of opening the details.

<details>
  <summary>
    <mat-form-field (click)="$event.stopPropagation()">
      <mat-label (click)="$event.stopPropagation()">First Name</mat-label>
      <input matInput value="Marvel" />
    </mat-form-field>
  </summary>
  details
</details>
1

There are 1 best solutions below

1
user16405471 On

Okay, I came up with this solution and it is working.

<details (click)="handleDetailsClick($event)">
  <summary>
    <mat-form-field>
      <mat-label>First Name</mat-label>
      <input matInput value="Marvel" />
    </mat-form-field>
  </summary>
  details
</details>

handleDetailsClick(event: MouseEvent): void {
    if ((event.target as Element).classList.contains('mat-form-field-infix')) {
      event.preventDefault();
    }
  }