Aquí, en mi mat-table, tengo 6 columnas cuando alguna columna no tiene más palabras, luego se ve como la Imagen-1, pero cuando cualquier columna tiene más palabras, la IU se ve como la Imagen-2, entonces, ¿cómo configurar la IU como la Imagen-1 cuando alguna ¿La columna tiene más palabras en angular 6?
Imagen-1
Imagen-2
usuario.componente.html
<div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="userimage"> <th mat-header-cell *matHeaderCellDef> # </th> <td mat-cell *matCellDef="let element"> <img src="{{commonUrlObj.commonUrl}}/images/{{element.userimage}}" style="height: 40px;width: 40px;"/> </td> </ng-container> <ng-container matColumnDef="username"> <th mat-header-cell *matHeaderCellDef> Full Name </th> <td mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td> </ng-container> <ng-container matColumnDef="emailid"> <th mat-header-cell *matHeaderCellDef> EmailId </th> <td mat-cell *matCellDef="let element"> {{element.emailid}} </td> </ng-container> <ng-container matColumnDef="contactno"> <th mat-header-cell *matHeaderCellDef> Contact No. </th> <td mat-cell *matCellDef="let element"> {{element.contactno}} </td> </ng-container> <ng-container matColumnDef="enabled"> <th mat-header-cell *matHeaderCellDef> Enabled </th> <td mat-cell *matCellDef="let element" style="color: blue"> <ng-container *ngIf="element.enabled == 'true'; else otherss">Enabled</ng-container> <ng-template #otherss>Disabled</ng-template> </td> </ng-container> <ng-container matColumnDef="action"> <th mat-header-cell *matHeaderCellDef> Action </th> <td mat-cell *matCellDef="let element" fxLayoutGap="5px"> <button mat-mini-fab color="primary" routerLink="/base/editUserDetails/{{element.userid}}"><mat-icon>edit</mat-icon></button> <button mat-mini-fab color="primary" routerLink="/base/viewUserDetails/{{element.userid}}"><mat-icon>pageview</mat-icon></button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 20, 50 ,100]" showFirstLastButtons></mat-paginator>Puedes hacerlo usando el siguiente CSS:
table { width: 100%; table-layout: fixed; } th, td { overflow: hidden; width: 200px; text-overflow: ellipsis; white-space: nowrap; } Aquí hay un StackBlitz Example con datos de muestra
podemos agregar el ancho del atributo directamente a th
p.ej:
<ng-container matColumnDef="position" > <th mat-header-cell *matHeaderCellDef width ="20%"> No. </th> <td mat-cell *matCellDef="let element"> {{element.position}} </td> </ng-container>usando css podemos ajustar el ancho de columna específico que puse en el código a continuación.
usuario.componente.css
table{ width: 100%; } .mat-column-username { word-wrap: break-word !important; white-space: unset !important; flex: 0 0 28% !important; width: 28% !important; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } .mat-column-emailid { word-wrap: break-word !important; white-space: unset !important; flex: 0 0 25% !important; width: 25% !important; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } .mat-column-contactno { word-wrap: break-word !important; white-space: unset !important; flex: 0 0 17% !important; width: 17% !important; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } .mat-column-userimage { word-wrap: break-word !important; white-space: unset !important; flex: 0 0 8% !important; width: 8% !important; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } .mat-column-userActivity { word-wrap: break-word !important; white-space: unset !important; flex: 0 0 10% !important; width: 10% !important; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; }Si está usando scss para sus estilos, puede usar un mixin para ayudar a generar el código. Sus estilos se saldrán de control rápidamente si pone todas las propiedades cada vez.
Este es un ejemplo muy simple: realmente no es más que una prueba de concepto, puede ampliarlo con varias propiedades y reglas según sea necesario.
@mixin mat-table-columns($columns) { .mat-column- { @each $colName, $props in $columns { $width: map-get($props, 'width'); &#{$colName} { flex: $width; min-width: $width; @if map-has-key($props, 'color') { color: map-get($props, 'color'); } } } } }Luego, en su componente donde se define su tabla, simplemente haga esto:
@include mat-table-columns(( orderid: (width: 6rem, color: gray), date: (width: 9rem), items: (width: 20rem) ));Esto genera algo como esto:
.mat-column-orderid[_ngcontent-c15] { flex: 6rem; min-width: 6rem; color: gray; } .mat-column-date[_ngcontent-c15] { flex: 9rem; min-width: 9rem; } En esta versión, el width se convierte en flex: value; min-width: value .
Para su ejemplo específico, podría agregar wrap: true o algo así como un nuevo parámetro.
Puedes hacer esto fácilmente. En cada columna, obtendrá una clase con el nombre del campo prefijado con mat-column, por lo que la clase será como mat-column-yourFieldName. Así que para eso puedes configurar el estilo como sigue
.mat-column-yourFieldName { flex: none; width: 100px; }Entonces podemos dar un ancho fijo para la columna según nuestro requisito.
Espero que esto ayude a alguien.
Aquí hay una forma alternativa de abordar el problema:
En lugar de intentar "arreglarlo en la publicación", ¿por qué no trunca la descripción antes de que la tabla deba intentar encajarla en sus columnas? Lo hice así:
<ng-container matColumnDef="description"> <th mat-header-cell *matHeaderCellDef> {{ 'Parts.description' | translate }} </th> <td mat-cell *matCellDef="let element"> {{(element.description.length > 80) ? ((element.description).slice(0, 80) + '...') : element.description}} </td> </ng-container>Entonces, primero verifico si la matriz es más grande que una cierta longitud, si es así, la trunco y agrego '...'; de lo contrario, paso el valor tal como está. Esto nos permite seguir beneficiándonos del espaciado automático que hace la tabla :)
Como he implementado, y está funcionando bien. solo necesita agregar el ancho de columna usando matColumnDef="description"
por ejemplo :
<mat-table #table [dataSource]="dataSource" matSortDisableClear> <ng-container matColumnDef="productId"> <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell> <mat-cell *matCellDef="let product">{{product.id}}</mat-cell> </ng-container> <ng-container matColumnDef="productName"> <mat-header-cell *matHeaderCellDef>Name</mat-header-cell> <mat-cell *matCellDef="let product">{{product.name}}</mat-cell> </ng-container> <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell> <mat-cell *matCellDef="let product"> <button (click)="view(product)"> <mat-icon>visibility</mat-icon> </button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row> </mat-table> aquí matColumnDef es productId , productName y action
ahora aplicamos ancho por matColumnDef
estilismo
.mat-column-productId { flex: 0 0 10%; } .mat-column-productName { flex: 0 0 50%; }y el ancho restante se asigna igualmente a otras columnas
Debajo de Css Class funcionó en Angular 13.2.3
.width-textArea { width: 150px; max-width: 150px; word-wrap: break-word; }La clase debía especificarse tanto en <th como en <Td
<ng-container matColumnDef="comments"> <th class="width-textArea" mat-header-cell *matHeaderCellDef mat-sort-header class="TableHeaderRow">Comments</th> <td class="width-textArea" mat-cell *matCellDef="let element"> {{element.comments}} </td> </ng-container>Solo agrega style="width:5% !important;" a th y td
<ng-container matColumnDef="username"> <th style="width:5% !important;" mat-header-cell *matHeaderCellDef> Full Name </th> <td style="width:5% !important;" mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td> </ng-container>Simplemente agregue la full-width-table de etiquetas.
por ejemplo <table mat-table class="full-width-table" [dataSource]="dataSource">
Puede usar fixedLayout="true" como <table #table mat-table [dataSource]="dataSource" fixedLayout="true">
fixedLayout: si se debe usar un diseño de tabla fijo. Habilitar esta opción impondrá anchos de columna consistentes y optimizará la representación de estilos pegajosos para tablas nativas. No-op para mesas flexibles.
ingrese la descripción de la imagen aquí Tenía una tabla con cuatro columnas. Por favor, vea la captura de pantalla. En el archivo scss, incluí el siguiente código:
.full-width-table { width: 100%; } .mat-column-id { width: 15% !important; } .mat-column-question { width: 55% !important; } .mat-column-view { width: 15% !important; } .mat-column-reply { width: 15% !important; }En caso de que desee dar un ancho fijo a una columna en particular, puede agregar fxFlex="60px" tanto a mat-cell como mat-header-cell .
Solo necesito actualizar el ancho de la etiqueta th .
th { width: 100px; }