Cpt Kitkat
Cpt Kitkat

Reputation: 1402

Filter not filtering data in mat-table

I have created a mat-table to display list of Jobs. Now I want to add a mat-filter to search a job using date or JobId. However the code that I have written doesn't seem to work. It does not throw any errors and it doesn't filter data.

HTML Code:

<mat-form-field>
        <input
            matInput
            (keyup)="applyFilter($event.target.value)"
            placeholder="Search"
        />
    </mat-form-field>
    <mat-table [dataSource]="jobExecutionList">
    ...

Typescript Code:

jobExecutionList: any = [];
applyFilter(filterValue: string) {
    this.jobExecutionList.filter = filterValue.trim().toLowerCase();
  }

Whole Typescript file :

import { Component, OnInit } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak- 
bar.component";
import { DataSource } from "@angular/cdk/collections";
import { Observable, of } from "rxjs";
import {
animate,
state,
style,
transition,
trigger
} from "@angular/animations";
import { RecommendationService } from "../recommendation-service.service";
import { MessageService } from '../../services/message.service';

@Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"],
animations: [
    trigger("detailExpand", [
        state(
            "collapsed",
            style({ height: "0px", minHeight: "0", visibility: "hidden" })
        ),
        state("expanded", style({ height: "*", visibility: "visible" })),
        transition(
            "expanded <=> collapsed",
            animate("225ms cubic-bezier(0.4, 0.0, 0.2, 1)")
        )
    ])
]
})
export class JobExecutionScreenComponent implements OnInit {
displaySpinner: boolean = false;
jobId: string;
jobExecutionList: any = [];
jobExecStatDisplayedColumns = [
    "jobId",
    "executionDate",
    "previousTimePeriod",
    "afterTimePeriod",
    "status",
    "actions",
    "spinner"
];
public selectedElem: any;
projectjobId: any = 1;
jobExecutionStat: any;
executionDate: string = new Date().toISOString().slice(0, 10);
executeJobStop: any;
changeStatus: any;
newStatus: any;
isExpansionDetailRow = (i: number, row: Object) =>
    row.hasOwnProperty("detailRow");
expandedElement: any;

constructor(
    private dataService: DataService,
    public globalAppSateService: GlobalAppSateService,
    private snakbar: SnakBarComponent,
    private recommendationService: RecommendationService,
    private messageService: MessageService
) {}
ngOnInit() {
    const project = JSON.parse(this.dataService.getObject("project"));
    if (project != null) {
        this.globalAppSateService.onMessage(project);
    }



    // API to get list of Running Jobs
    this.recommendationService
        .getJobExecutionStatList(this.projectjobId)
        .subscribe(data => {
            this.jobExecutionList = data;
            console.log(this.jobExecutionList);
            // this.jobExecutionStat = new ExampleDataSource();
        });
}
applyFilter(filterValue: string) {
    this.jobExecutionList.filter = filterValue.trim().toLowerCase();
  }

stop_exec_job(element) {
    if (element.status == "Running" || element.status == "Pending") {
        //Api to stop Job Execution
        this.recommendationService
            .stopJobExecution(element.jobId, "Cancelled")
            .subscribe(data => {
                this.executeJobStop = data;
                //this.changeStatus.push(this.executeJobStop);
                // this.newStatus = new ExampleDataSource();
            });
        this.displaySpinner = false;
        element.status = "Cancelled";
        this.snakbar.statusBar("Job Execution Stopped", "Sucess");
    } else {
        this.snakbar.statusBar("Job Failed to start", "Failure");
    }
}

// Will need it for mat-progress bar
// stop_exec_job2() {
//     this.stop_exec_job(this.selectedElem);
//     this.displaySpinner = false;
// }

re_run_job(element) {
    if (
        element.status == "Cancelled" ||
        element.status == "Completed" ||
        element.status == "Executed" ||
        element.status == "FINISHED"
    ) {
        //Api to Re-Run Job Execution
        this.recommendationService
            .stopJobExecution(element.jobId, "Running")
            .subscribe(data => {
                this.executeJobStop = data;
                //this.changeStatus.push(this.executeJobStop);
                // this.newStatus = new ExampleDataSource();
            });
        this.displaySpinner = true;
        element.status = "Running";
        this.snakbar.statusBar("Job Execution Started", "Sucess");
        this.messageService.messageReceived$.subscribe(data => {
            this.snakbar.statusBar(
                'Platform job status - ' + data,
                'Info'
            );
            //this.isLoadingResults = false;
        });
    } else {
        this.snakbar.statusBar("Job Failed to start", "Failure");
    }
}

}
export interface Element {
jobId: number;
executionDate: string;
previousTimePeriod: string;
afterTimePeriod: string;
status: string;
}

This is the Whole typescript file.

Upvotes: 2

Views: 8664

Answers (2)

B.Benjo
B.Benjo

Reputation: 573

Based on different comment, you need to do:

dataSource: MatTableDataSource<any>;

And then when you get the data:

this.dataSource = new MatTableDataSource(/** YOUR DATA **/);

In your example:

import { Component, OnInit } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak- 
bar.component";
import { DataSource } from "@angular/cdk/collections";
import { Observable, of } from "rxjs";
import {
animate,
state,
style,
transition,
trigger
} from "@angular/animations";
import { RecommendationService } from "../recommendation-service.service";
import { MessageService } from '../../services/message.service';

@Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"],
animations: [
    trigger("detailExpand", [
        state(
            "collapsed",
            style({ height: "0px", minHeight: "0", visibility: "hidden" })
        ),
        state("expanded", style({ height: "*", visibility: "visible" })),
        transition(
            "expanded <=> collapsed",
            animate("225ms cubic-bezier(0.4, 0.0, 0.2, 1)")
        )
    ])
]
})
export class JobExecutionScreenComponent implements OnInit {
displaySpinner: boolean = false;
jobId: string;
jobExecutionList: MatTableDataSource<any>;
jobExecStatDisplayedColumns = [
    "jobId",
    "executionDate",
    "previousTimePeriod",
    "afterTimePeriod",
    "status",
    "actions",
    "spinner"
];
public selectedElem: any;
projectjobId: any = 1;
jobExecutionStat: any;
executionDate: string = new Date().toISOString().slice(0, 10);
executeJobStop: any;
changeStatus: any;
newStatus: any;
isExpansionDetailRow = (i: number, row: Object) =>
    row.hasOwnProperty("detailRow");
expandedElement: any;

constructor(
    private dataService: DataService,
    public globalAppSateService: GlobalAppSateService,
    private snakbar: SnakBarComponent,
    private recommendationService: RecommendationService,
    private messageService: MessageService
) {}
ngOnInit() {
    const project = JSON.parse(this.dataService.getObject("project"));
    if (project != null) {
        this.globalAppSateService.onMessage(project);
    }



    // API to get list of Running Jobs
    this.recommendationService
        .getJobExecutionStatList(this.projectjobId)
        .subscribe(data => {
            this.jobExecutionList = new MatTableDataSource(data);
            console.log(this.jobExecutionList);
            // this.jobExecutionStat = new ExampleDataSource();
        });
}
applyFilter(filterValue: string) {
    this.jobExecutionList.filter = filterValue.trim().toLowerCase();
  }

Upvotes: 6

Anil Kumar Reddy A
Anil Kumar Reddy A

Reputation: 648

I already have an example for this kind, you can look over this.

Mat-Table-stackblitz

Upvotes: 1

Related Questions