Solvedcomponents Default sorting in Sort header


How can I change Angular Material code below, so that data-table is sorted by 'name' column, ascending order by default. Arrow (indicating current sort direction) must be displayed.

<table matSort (matSortChange)="sortData($event)">
    <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 *ngFor="let dessert of sortedData">

What is the expected behavior?


What is the current behavior?

I was trying something like this, to show arrow (indicating sort order) but it doesn't work.

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

What are the steps to reproduce?

Here's link to Plunker
StackOverflow Question

17 Answers

✔️Accepted Answer

You're mistaking matSortStart for matSortDirection.

Try this:

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

matSortStart can be used to reverse the cycle used when sort (e.g. when the user clicks to sort, it starts at desc instead of asc).

Other Answers:

You can do it like this:

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit(): void {
        id: 'id',
        start: 'desc'

// And we should remember that matSortActive shall go along with matSortDirection, to start working.

gotta love the sort.sort

@ichepurnoy yes, I set both but nothig... maybe is a bug. I have something like this:

<table matSort (matSortChange)="sortData($event)" matSortActive="{{ sortActive }}" matSortDirection="{{ sortDirection }}" matSortDisableClear>

If I set the sortActive and sortDirection values in the ngOnInit it works okay dynamically, but after the view init if I try to change those values is not working.

Related Issues:

components Error: mat-form-field must contain a MatFormFieldControl.
You have to add to app.module.ts: Bug feature request or proposal: When doing a karma/jasmine test I...
components [Table] Add example with dynamic columns
For those interested Bug feature request ...
components [Table] Throw error if MatSortModule is not imported while using "MatSort/matSort"
In came here because I hit the error @tzachs reported above: In my case the issues was that by accid...
components Can't drag md-slider
The import order solution never worked for me though it does seem to be related to something overrid...
components animation trigger "transformMenu" has failed to build
Sorry for commenting on a closed issue but got the same error when upgrading to Angular 5 using JEST...
components When using @ViewChild element.nativeElement is undefined
@gouldina Please refer to the link that @willshowell posted above Basically just do @ViewChild('name...
components Fixed header rows for md-table
to simplify above solution Write Bug feature request ...
components form-field: remove extra bottom space
10px is not enough considering size of padding <mat-form-field style= margin-bottom: -1.25em> I agre...
components Angular CLI + Angular Material {MatButtonModule} breaks angular build
Open your package.json file just change these to whatever the current version of the other angular c...
components strictTemplates, Angular 9: compability with Ivy
Dunno if it helps Enabling the new strictTemplates flag in Angular 9's compiler options generates th...
components [Table] - Add example with multiple filtering columns
@erickyi2006 I am using mat-menu mat-select mat-input everywhere to meet my requirements for the mat...
components NullInjectorError: No provider for MatDialogRef!
@jepetko Thanks for that worked I also had this in my dialog component constructor: @Inject(MAT_DIAL...
components No provider for MatDialogRef!
You will get that exact No provider for MatDialogRef error in case you include your dialog's compone...
components Opening MdDialog in ngOnInit throws ExpressionChangedAfterItHasBeenCheckedError
I had the same problem here when I tried open the MatDialog: ExpressionChangedAfterItHasBeenCheckedE...
components MdPaginatorIntl Internationalization example
@mhosman @rsaulo This is how I did it in @angular/material: ^5.0.3 Create separate file e.g ...
components Mat-tooltip bug: The pipe 'async' could not be found
Setting enableIvy: false (or simply removing it) in angularCompilerOptions (tsconfig.json) resolved ...
components Cannot find module... Problems with cdk
Did you install @angular/cdk? Bug feature request ...
components matTable - DataSource issue
@teoCasasbuenas @pablitodeveloper change: to If you're using version 5.2.4 of @angular/material http...
components Can't bind to 'ngModel' since it isn't a known property of 'md-input'.
You probably need to import the FormsModule in you app.module. I've seen some similar issues of peop...
components proposal: the current and the future state of material2
I agree we could definitely be more clear about the current status of the project For the most part ...
components Default sorting in Sort header
You're mistaking matSortStart for matSortDirection Question: How can I change Angular Material code ...
components Error Setting Up Custom Material Theme in Angular-CLI Project
Had the same issue with CLI: 1.6.4 node: 9.2.0 Angular: 5.0.0 Material: 5.0.4 just need to remove th...
components MatTable: Cannot read property 'nativeElement' of undefined
Well nevermind I found the issue Somehow my target property in tsconfig.json had the value of 'es201...
components Plunkers not working for md-data-table examples
Adding import { CdkTableModule } from '@angular/cdk'; to main.ts and add CdkTableModule to the impor...
components Does not package with ng-packagr
@willshowell adding material to lib.externals in ng-package.json: seems to have fixed my issue my li...
components [feature] Improve datepicker documentation for date format
@Robouste Right now you have to write your own DateAdapter. That is the only workaround that I found...
components Illegal state: Could not load the summary for directive ObserveContent
OK after numerous hours working on a reproduction and then changing code/config one at a time and re...
components [Table] Ability to filter complex objects
Sounds like you want a custom filter function which you can do by overriding the filterPredicate ...
components No documentation exists for Jasmine unit tests of Angular components containing @angular/material
I can add some of the things I've come across which might help out others looking for info Hopefully...
components Error: StaticInjectorError[BreakpointObserver] No provider for BreakpointObserver
my fail I tried: import {MatSnackBarModule} from @angular/material/snack-bar; but I have to: import ...
components feat(stepper): support lazy rendering of steps
Not sure if I am just stating the obvious Bug feature request ...
components Can't bind to 'mdMenuTriggerFor' since it isn't a known property of 'button'
I am getting the same error when running tests Bug feature request ...
components mat-table: Rows and table elements widths don't grow according to cell widths
The following workaround worked perfectly for me Bug feature request or proposal: Bug ...
components Cannot customize style of md-tabs
You need to use /deep/: Bug feature request ...
components Not able to compile custom theme
Looks like they've changed the Github build of Material I'm not able to set the custom material them...
components Theming your own component doc incorrectly references pre-built theme
Thank you all to the contributions to this thread after fighting with the docs this was a very usefu...
components [Paginator] Unclear in docs about how to set language
//Atribute @ViewChild(MatPaginator) paginator: MatPaginator; ngOnInit(){ .. Bug feature request or p...
components Add documentation for MomentDateAdapter usage
Full process for using Moment objects instead of Date objects npm i @angular/material-moment-adapter...
components Getting "No component factory" error while opening a Material Dialog in lazy loaded Component
You need to import MatDialogModule in ConsumerModule in order for it to know about the entryComponen...
components Weird ripple effect
I have got the same problem Each click of the bottom inserts a Into my html and it keeps stacking an...
components Slide Toggle Doesn't Seem to be working in Alpha 7 Error: Cannot find name 'HammerInput'
For those finding this issue that have a similar configuration to mine: angular-material: 2.0.0-alph...
components Add guidance for styling invalid inputs
For the time being I'm using a md-hint to show my error messages: It might help someone ...
components Add Customize Css Class to the Mat-Tab-Content and other Mat-X tags which are generated runtime
Why is this closed? <mat-tab> classes are not applied anywhere Bug feature request ...
components Snackbar + md-icon
Use a custom snackbar component: customsnackbar.component.ts: app.component.ts: app.module.ts: ...
components [Table] simpler example without example database
Anyway it would be possible to design a table completely in HTML Without data source binding Like: O...
components Md-expansion panel opened and close events not firing on prod build (beta.11)
Thanks @josephperrott If you're like me and just upgraded your project and even ran the md -> mat up...
components Custom Theme issue
Your $primary $accent etc are not what the theme function is expecting If you look at our pre-built ...
components [MdSidenav] - Sidenav Resizing Regression
Here is my solution: HTML TS Bug feature request or proposal: Bug/Regression from 2.0.0-beta.8 ...
components Docs bug: How to add rows to table
MatTableDataSource does not have the renderRows method It's in CdkTable | MatTable However in Angula...
components (suggestion)md-table with http example
Hey @lemang Here is my code 👨‍💻 Bug feature request ...