简体   繁体   中英

In mat-table, edit the column header

I'm using the angular material mat table in which I want to edit the column header name. Suppose columns header list is Name, Age, Gender etc. User wants to rename the header Name's Age to Date of birth then how is it possible. which process I can follow for this.

You can display columns header as input field, but this may cause a bad UX. I suggest to use an icon (button) or double click event to enable editing:

编辑gif


You can try:

HTML:

...
<ng-container [matColumnDef]="value">
    <th mat-header-cell *matHeaderCellDef>
      <span
        *ngIf="!enableEditing"
        (dblclick)="enableEditing = true"
        style="cursor: pointer"
      >
        {{value | titlecase}}
      </span>
      <input
        *ngIf="enableEditing"
        type="text"
        [(ngModel)]="value"
        (keydown.enter)="editName()"
        (focusout)="editName()"
      />
    </th>
    <td mat-cell *matCellDef="let element">{{element.name}}</td>
  </ng-container>
...

And editName() to save change:

editName() {
  this.displayedColumns = ['position', this.value, 'weight', 'symbol'];
  this.enableEditing = false;
}

Stackblitz demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM