我正在开发angular应用程序。在这方面,我使用了具有列切换功能的素数表。我的代码如下
HTML-
<p-table [columns]="selectedColumns" [value]="products">
<ng-template pTemplate="caption">
<p-multiSelect [options]="cols" [(ngModel)]="selectedColumns" optionLabel="header"
selectedItemsLabel="{0} columns selected" [style]="{minWidth: '200px'}" placeholder="Choose Columns"></p-multiSelect>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th>Code</th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-product let-columns="columns">
<tr>
<td>{{product.code}}</td>
<td *ngFor="let col of columns">
{{product[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
组件-
import { Component, OnInit, Input } from '@angular/core';
import { Product } from './product';
import { ProductService } from './productservice';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
products: Product[];
cols: any[];
_selectedColumns: any[];
constructor(private productService: ProductService) { }
ngOnInit() {
this.productService.getProductsSmall().then(data => this.products = data);
this.cols = [
{ field: 'name', header: 'Name' },
{ field: 'category', header: 'Category' },
{ field: 'quantity', header: 'Quantity' }
];
this._selectedColumns = this.cols;
}
@Input() get selectedColumns(): any[] {
return this._selectedColumns;
}
set selectedColumns(val: any[]) {
//restore original order
this._selectedColumns = this.cols.filter(col => val.includes(col));
}
}
Stackblitz-
https://stackblitz.com/edit/primeng-tablecoltoggle-demo?file=src%2Fapp%2Fapp.component.ts
代码运行良好,但我希望在coltoggle中使用反向功能。默认情况下,列在下拉列表中打勾,如果用户想删除任何列,他可以取消选中。我想实现完全相反的方式,即默认情况下下拉列表中的所有列都应该取消选中,如果用户希望查看任何列的数据,他可以在下拉列表中打勾,并可以查看有数据的列。我该怎么做?
只需将所选列设置为一个空数组即可开始。
ngOnInit() {
this.productService.getProductsSmall().then(data => this.products = data);
this.cols = [
{ field: 'name', header: 'Name' },
{ field: 'category', header: 'Category' },
{ field: 'quantity', header: 'Quantity' }
];
this._selectedColumns = []; // just leave an empty array from the start
}