PrimeNG表格初始化时通过TS代码过滤后二次过滤报错及过滤器格式不一致问题
Got it, let's break down what's happening here and fix that error for you.
The root issue is a mismatch in filter formats: when you use this.dt.filter() to set the initial filter on load, it stores the woid filter as a single object. But when you use <p-columnFilter> for the customer column, PrimeNG creates an array of filter objects (to support multi-condition filtering). This inconsistency throws the NgFor error later, because Angular tries to loop over the woid object like it would an array.
Here's how to fix it by aligning the initial filter structure with what <p-columnFilter> uses:
Step 1: Initialize Filters with the Correct Array Format
Instead of calling dt.filter(), directly set the table's filters property to match the array-based structure that <p-columnFilter> generates. This ensures consistency across all filtering operations.
import { Table } from 'primeng/table'; // Import the specific Table type @Component({ // Your component metadata }) export class YourComponent { @ViewChild('dt', { static: true }) dt: Table; // Use Table instead of 'any' for type safety ngOnInit() { // Initialize filters with the same array structure as p-columnFilter this.dt.filters = { woid: [{ value: '22', matchMode: 'contains', operator: 'and' // Match the default multi-condition operator }] }; // Trigger the filter to apply the initial value this.dt.filter(); } onFiltering(event: any) { console.log('Filtered value: '+ JSON.stringify(event.filters)); } }
Why This Works
After this change, both your initial woid filter and the customer filter from <p-columnFilter> will use the same array-based structure. Your event.filters output will now look consistent:
{ "woid": [{ "value": "22", "matchMode": "contains", "operator": "and" }], "customer": [{ "value": "2", "matchMode": "contains", "operator": "and" }] }
This eliminates the type mismatch that caused the NgFor error, and all subsequent filtering operations (whether via code or the UI) will work as expected.
A quick bonus tip: Using the Table type instead of any gives you better type hints and catches errors early in development.
内容的提问来源于stack exchange,提问作者Domagoj Hamzic

