user6999
user6999

Reputation: 51

Stop event propagation for mat-select inside mat-checkbox

I have a <mat-select> inside a <mat-checkbox>. When there is a change on <mat-select>, it also toggles the <mat-checkbox> and I do not want this to happen.

I have tried using '$event.stopPropagation()' but it doesn't work. Any ideas how this could be tackled?

<mat-checkbox [(ngModel)]="myCheckboxModel" (change)="onChangeFunction()">
    <mat-form-field>
        <mat-select [(ngModel)]="mySelectModel">
            <mat-option value="1">1</mat-option>
            <mat-option value="2">2</mat-option>
        </mat-select>
    </mat-form-field>
</mat-checkbox>

Upvotes: 5

Views: 5669

Answers (3)

M.H
M.H

Reputation: 89

It works for me by prevent click event outside

          <mat-form-field [appearance]="'standard'" (click)="$event.stopPropagation()">
            <mat-label>Label</mat-label>
            <mat-select [(ngModel)]="type">
              <mat-option *ngFor="let typeItem of typeSelection" [value]="typeItem.code">{{typeItem.name}}</mat-option>
            </mat-select>
          </mat-form-field>

Upvotes: 0

roniccolo
roniccolo

Reputation: 158

For me it worked adding (keydown.enter)="$event.preventDefault()"

<mat-checkbox [(ngModel)]="myCheckboxModel (keydown.enter)="$event.preventDefault()">Checkbox Label</mat-checkbox>

Upvotes: 0

Simon_Weaver
Simon_Weaver

Reputation: 146160

I have the same issue with nested mat-selection-list items.

This is working for me.

selectionChange(event: MatSelectionListChange)
{
    window['event']?.stopPropagation();
}

I'm just finding out today that window.event is deprecated, but in this exact context it's not easy since angular doesn't give us the underlying event.

If you're using SSR make sure not to call this programatically since window is not defined.

Upvotes: 3

Related Questions