无法设置 Angular Material matColumnDef 属性

Cannot set Angular Material matColumnDef property

我有一个数据表,想更改 matColumnDef 属性 的值。但是,当我将它与 [matColumnDef] 一起使用时,我无法更改它,如下所示:

<ng-container *ngIf="hasButton" [matColumnDef]="action">

另一方面,当不带括号 matColumnDef 更改其值时,相关部分不会呈现在页面上。那么,[matColumnDef]matColumnDef有什么区别呢?以及为什么我不能设置免费值?

<ng-container *ngIf="hasButton" matColumnDef="action">

我不太确定你的 table 是如何设置的,但我可以让它在这个通用示例中正常工作

控制器

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: "Hydrogen", weight: 1.0079, symbol: "H" },
  { position: 2, name: "Helium", weight: 4.0026, symbol: "He" },
  { position: 3, name: "Lithium", weight: 6.941, symbol: "Li" },
  { position: 4, name: "Beryllium", weight: 9.0122, symbol: "Be" },
  { position: 5, name: "Boron", weight: 10.811, symbol: "B" },
  { position: 6, name: "Carbon", weight: 12.0107, symbol: "C" },
  { position: 7, name: "Nitrogen", weight: 14.0067, symbol: "N" },
  { position: 8, name: "Oxygen", weight: 15.9994, symbol: "O" },
  { position: 9, name: "Fluorine", weight: 18.9984, symbol: "F" },
  { position: 10, name: "Neon", weight: 20.1797, symbol: "Ne" }
];

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: "table-basic-example",
  styleUrls: ["table-basic-example.css"],
  templateUrl: "table-basic-example.html"
})
export class TableBasicExample {
  action: string;
  displayedColumns: string[] = ["position"];
  dataSource = ELEMENT_DATA;

  showColumn(column: string) {
    this.action = column;
    this.displayedColumns = ["position", column];
  }
}

模板

<button md-raised-button color="primary" (mouseup)="showColumn('name')">
  Show Name
</button>
<button md-raised-button color="primary" (mouseup)="showColumn('weight')">
  Show Weight
</button>
<button md-raised-button color="primary" (mouseup)="showColumn('symbol')">
  Show Symbol
</button>

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef>No.</th>
    <td mat-cell *matCellDef="let element">{{element.position}}</td>
  </ng-container>

  <!-- Name Column -->
  <ng-container [matColumnDef]="action">
    <th mat-header-cell *matHeaderCellDef>{{ action }}</th>
    <td mat-cell *matCellDef="let element">{{element[action]}}</td>
  </ng-container>

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

工作示例:Stackblitz

需要注意的重要一点是根据要显示的列修改displayedColumns变量。