I'm using Angular 9. I have a simple mat-table with three columns ...
<mat-table *ngIf="!isMobile" #table [dataSource]="dataSource">
<ng-container matColumnDef="time">
<mat-header-cell *matHeaderCellDef> Time </mat-header-cell>
<mat-cell *matCellDef="let article_stat">{{ getTime(article_stat) }} m</mat-cell>
</ng-container>
<ng-container matColumnDef="score">
<mat-header-cell *matHeaderCellDef> score </mat-header-cell>
<mat-cell *matCellDef="let article_stat">
{{ getscore(article_stat) }} ({{ getWeightedscore(article_stat) }})
</mat-cell>
</ng-container>
<ng-container matColumnDef="article">
<mat-header-cell *matHeaderCellDef> Article </mat-header-cell>
<mat-cell *matCellDef="let article_stat">
<a href='{{ article_stat.article.path }}'>{{ article_stat.article.title }}</a>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="getRowClass(row)"></mat-row>
</mat-table>
Below is my simple CSS for the component. There is no CSS at the app component level ...
.mat-table {
width: auto;
}
.rising {
font-weight: bold;
}
However, when my table is rendered, it is taking up 100% of the screen, despite the fact the data in each column does not occupy that much space. If I change the width to a fixed pixel width, (e.g. "200px"), browsers respect the wdith. Why isn't "width: auto" working and how do I style my mat-table such that it only takes up as much space as the data within it?
I have looked at the documentation from Angular concerning "mat-table".
In the examples given they are using the table element with "mat-table" included in the beginning table tag:
HTML
<table mat-table [dataSource]="dataSource">
CSS:
table {
width: auto;
}
I have tested the css of width: auto;
and it is working as expected - This was pulled straight from the Angular documentation and tested in stackbliz. You can view my working test here.
Edit:
To be more clear, at the bottom of the documentation page listed above there is a note for using Tables with display: flex
(<mat-table>
instead of <table mat-table>
).
Note that this approach means you cannot include certain native-table features such colspan/rowspan or have columns that resize themselves based on their content.