Angel Treviño
Angel Treviño

Reputation: 71

Disable MatSort on space key pressed Angular Material

So I'm using angular material tables and decided to made a filter for each column. The inputs for this filters are located in the row header of each column. That works fine, but the thing is when I'm typing and pressed the space key, the table gets sorted. I want this behavior to stop, but if I used (keydown.space)="$event.preventDefault()" but the space isn't inserted in the input. Here is the code below of the table.

<table mat-table class="full-width-table" (matSortChange)="sortData($event)" [dataSource]="this.datasrcCollIndex" aria-label="Elements" matSort matSortActive="strName" matSortDirection="asc" matSortDisableClear>

        <!-- Name Column -->
        <ng-container matColumnDef="strName">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
                <mat-form-field style="margin-top: 0px;">
                    <input matInput placeholder="Name" (keyup)="filteringByColumns()"  [(ngModel)]="strName" >
                </mat-form-field>
            </th>
            <td mat-cell *matCellDef="let user">{{user.strName}}</td>
        </ng-container>

        <!-- Gender Column -->
        <ng-container matColumnDef="strGender">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
                <mat-form-field style="margin-top: 0px; width: 70px;">
                    <input matInput placeholder="Gender" (keyup)="filteringByColumns()" [(ngModel)]="strGenderColumn">
                </mat-form-field>
            </th>
            <td mat-cell *matCellDef="let user">{{user.strGender}}</td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="this.dictstrDisplayedColumns"></tr>
        <tr mat-row (click)="this.showDetailsOfUsers(user)"
            *matRowDef="let user; columns: this.dictstrDisplayedColumns;"></tr>

    </table>

Upvotes: 7

Views: 2501

Answers (2)

ESipalis
ESipalis

Reputation: 431

Instead of using

preventDefault()

I used

stopPropagation()

it still allows input to be entered, but does not propagate the event to the parent elements (thus the sorting element never receiving the event). Usage:

(keydown.space)="$event.stopPropagation()"

Upvotes: 5

Andrei Diaconescu
Andrei Diaconescu

Reputation: 648

i had the same problem and did:

event.preventDefault();
(event.target as any).value += ' ';

Upvotes: 0

Related Questions