我有一个数据表,并且想要更改matColumnDef
属性的值。但是,与[matColumnDef]
结合使用时,如下所示,我无法更改它:
<ng-container *ngIf="hasButton" [matColumnDef]="action">
另一方面,如果在不使用括号matColumnDef
的情况下更改其值,则相关部分不会呈现在页面上。那么,[matColumnDef]
和matColumnDef
有什么区别?为什么我不能通过自由值来设置它?
<ng-container *ngIf="hasButton" matColumnDef="action">
答案 0 :(得分:1)
我不确定您的表如何设置,但是在这个通用示例中我可以使它工作
控制器
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
变量。