1

How can I filter an entire column (header and data) with Angular2 data-table?

I am able to filter the column data but the header remains..:

https://stackblitz.com/edit/data-table-filter-columns

EDIT:

This is actually very easy and an oversight by me. The solution was just to add my filtering function to the matHeaderRowDef as well as the matRowDef. I've updated my stackblitz so it is now working as I intended

1 Answer 1

1

I give you just an example as solution, because it isn't hard and you can find the solution in the docs. Just adopt this situation to yours.

Try the approach like in the docs, so seperate the displayed data for columns, rows and generel data for the table.

const ELEMENT_DATA: PeriodicElement[] = [
    {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
    {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
];
data: PeriodicElement[] = ELEMENT_DATA;

displayedColumns: string[] = ['name', 'weight', 'symbol', 'position'];

columnsToDisplay: string[] = this.displayedColumns.slice(); //returns a copy of displayedColumns

Now you can use those in your html file like the following:

<table mat-table [dataSource]="data">
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
        <th mat-header-cell *matHeaderCellDef> {{column}} </th>
        <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
    </ng-container>

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

As an example to your solution I will add an button in the html file to trigger removing the last column: (is the same as sorting in some way)

<button mat-raised-button (click)="removeColumn()"> Remove column </button>

Now we just have to remove the last element of the array displayedColumns in order the remove the last column of our table.

removeColumn() {
    this.columnsToDisplay.pop(); //removes the last element of the array
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer. Yes it was just me being stupid and i missed the matHeaderRowDef, i've updated my stackblitz so it now works as intended

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.