tutorial angular angular-material

tutorial - Clasificación predeterminada en material angular-Ordenar encabezado



mat-table (3)

¿Quizás ha intentado llamar al inicio de la página la función de ordenamiento forzada en nombre y dirección?

ngOnInit() { let defSort: Sort = {}; defSort.direction = ''asc''; defSort.active = ''name''; this.sortData(defSort); }

¿Cómo puedo cambiar el código de Material Angular a continuación, para que la tabla de datos esté ordenada por columna de "nombre", en orden ascendente de forma predeterminada? Se debe mostrar la flecha (que indica la dirección de clasificación actual).

Esto es lo que quiero lograr:

Código original:

<table matSort (matSortChange)="sortData($event)"> <tr> <th mat-sort-header="name">Dessert (100g)</th> <th mat-sort-header="calories">Calories</th> <th mat-sort-header="fat">Fat (g)</th> <th mat-sort-header="carbs">Carbs (g)</th> <th mat-sort-header="protein">Protein (g)</th> </tr> <tr *ngFor="let dessert of sortedData"> <td>{{dessert.name}}</td> <td>{{dessert.calories}}</td> <td>{{dessert.fat}}</td> <td>{{dessert.carbs}}</td> <td>{{dessert.protein}}</td> </tr> </table>

Estaba intentando algo como esto, pero no funciona (no se muestra una flecha, no está ordenada)

<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortStart="asc" matSortDisableClear>

Aquí hay enlace a Plunker


Estás confundiendo matSortStart con matSortDirection .

Prueba esto:

<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortDirection="asc" matSortDisableClear>

https://plnkr.co/edit/sg0hC5d8LTjLKhbH9Eug?p=preview

matSortStart se puede usar para revertir el ciclo usado al ordenar (por ejemplo, cuando el usuario hace clic para ordenar, comienza en desc en lugar de asc).


Puede ordenar la tabla mediante programación invocando el método de sort(Sortable) del origen de datos. Suponiendo que tiene una propiedad de componente dataSource para la fuente de datos:

// to put next to the class fields of the component @ViewChild(MatSort) sort: MatSort // to put where you want the sort to be programmatically triggered, for example inside ngOnInit this.sort.sort(<MatSortable>({id: ''name'', start: ''asc''})); this.dataSource.sort = this.sort;