如何使用 ng-template 过滤 PrimeNg DataTable 列?

How to filter over a PrimeNg DataTable column with ng-template?

这是我的专栏:

<p-column header="Roles" sortable="true" [filter]="true" filterMatchMode="contains">
  <ng-template let-user="rowData" pTemplate="body">
    <div *ngFor="let role of user.roles">
      {{role.name}}
    </div>
  </ng-template>
</p-column>

例子 user.roles JSON:

[ { "id": 3, "name": "A single role" } ]
[ { "id": 4, "name": "A role name" }, { "id": 6, "name": "Another role name" } ]

我想在上面添加一个过滤器 - 我尝试添加这个 ng-template:

<ng-template pTemplate="filter" let-col let-test="rowData">
        <p-multiSelect [options]="roles" defaultLabel="All roles" (onChange)="dt.filter($event.value,test.roles,col.filterMatchMode)"
          styleClass="ui-column-filter"></p-multiSelect>
 </ng-template>

多选选项在单独的角色数组中:

this.roles = [];
this.roles.push({ label: 'A role', value: 'aRole' });
this.roles.push({ label: 'Another role', value: 'anotherRole' });

...但由于某种原因,我收到此错误:

Cannot read property 'roles' of undefined

像这样尝试:

检查你的 primeng node_module 版本我正在做 4.2.1 primeng

module.ts

像您的 app.module 文件一样导入 DataTableModule 和 MultiSelectModule

import { DataTableModule, MultiSelectModule } from 'primeng/primeng';

@NgModule({
    imports: [
        DataTableModule,
        MultiSelectModule
    ]
})

component.ts

export class AppComponent implements OnInit {

    private users: Array<any> = [];
    private roles: Array<any> = [];

    constructor() { }

    ngOnInit() {
        this.users = [];
        this.users.push({ "id": 3, "name": "anotherRole" });
        this.users.push({ "id": 4, "name": "aRole" }, { "id": 6, "name": "anotherRole" });


        this.roles = [];
        this.roles.push({ label: 'A role', value: 'aRole' });
        this.roles.push({ label: 'Another role', value: 'anotherRole' });
    }
}

component.html

<p-dataTable [value]="users" [rows]="4" [paginator]="true" [globalFilter]="gb" #dt>
<p-header>List of Cars</p-header>
<p-column field="id" header="ID"></p-column>
<p-column field="name" header="Name" [filter]="true" filterMatchMode="in">
    <ng-template pTemplate="filter" let-col>
        <p-multiSelect [options]="roles" defaultLabel="All Colors" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-multiSelect>
    </ng-template>
</p-column>
</p-dataTable>

按照官方论坛的说法,我想要的是不可能的。需要 "field"。作为一种解决方法,我将我的角色数组展平为一个字符串并将其显示在一个字段中。我现在可以用匹配模式 "contains"

过滤它