1

I am using mat-table, the displayed columns are defined in the following array:

TypeScript:

displayedColumns: string[] = ['date', 'customer', 'project', 'performanceRecord', 'duration', 'status', 'action'];

HTML:

<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

For mobile phones, i would like to remove some columns and replace the displayedColumns with displayedColumnsForMobilePhones:

displayedColumnForMobilesPhones: string[] = ['date', 'customer', 'project'];

So i would like to know whether there is a way to change the displayed columns depending on screen size. Is something like this possible?

<tr mat-header-row *matHeaderRowDef="getScreenSize() > XS ? displayedColumn : displayedColumnForMobilePhones; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: getScreenSize() > XS ? displayedColumn : displayedColumnForMobilePhones;"></tr>

Or is there any other way to figure out the screensize and adjust the displayedColumn array accordingly? Anything would work, thanks.

M.Dietz
  • 900
  • 10
  • 29

1 Answers1

2

You can use BreakpointObserver of Angular Material.

Another way is to capture the window:resize event and change the displayed column.


@HostListener('window:resize', ['$event'])
onResize(event) {

  if(event.target.innerWidth < 600 && !isColumnsMobile) {

    this.displayedColumns = this.displayedColumnForMobilesPhones;
    this.isColumnsMobile = true;

  } else if(event.target.innerWidth >= 600 && isColumnsMobile) {

    this.displayedColumns = this.initialDisplayedColumns;
    this.isColumnsMobile = false;

  }

}

You can try to tweak this example to your needs.

There are more ways to implement this, but the idea is the same so changing displayedColumns will reset the columns as you wish.

noririco
  • 765
  • 6
  • 15
  • 1
    Thanks, that worked out, i just had to replace the `event.target.innerWidth` with `event.target.screen.availWidth`. I guess i also have to put a similar code of block into the onInit method, because the resize event does not get triggered on the first load, just whenever you resize it afterwards. Or should i just manually call the onResize method within the onInit method? – M.Dietz Oct 16 '19 at 13:56
  • Okay i was able to set the displayedColumns inside the onInit method by using the `window.screen.width` property. Everything works now, thanks. – M.Dietz Oct 16 '19 at 14:05
  • @M.Dietz you are awesome! – noririco Oct 16 '19 at 14:07