Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

4.4K
Views
¿Cómo establecer el ancho de la columna mat-table en angular?

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

ingrese la descripción de la imagen aquí

Imagen-2

ingrese la descripción de la imagen aquí

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>

over 4 years ago · Santiago Trujillo
14 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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; }
over 4 years ago · Santiago Trujillo Report

0

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>
over 4 years ago · Santiago Trujillo Report

0

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 compruebo 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 :)

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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>
over 4 years ago · Santiago Trujillo Report

0

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; }
over 4 years ago · Santiago Trujillo Report

0

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 .

over 4 years ago · Santiago Trujillo Report

0

Solo necesito actualizar el ancho de la etiqueta th .

 th { width: 100px; }
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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>
over 4 years ago · Santiago Trujillo Report

0

Simplemente agregue la full-width-table de etiquetas.

por ejemplo <table mat-table class="full-width-table" [dataSource]="dataSource">

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!