【问题标题】:Filter not filtering data in mat-table过滤不过滤 mat-table 中的数据
【发布时间】:2019-06-22 11:30:37
【问题描述】:

我创建了一个垫表来显示工作列表。 现在我想添加一个垫过滤器来使用日期或 JobId 搜索工作。 但是,我编写的代码似乎不起作用。 它不会抛出任何错误,也不会过滤数据。

HTML 代码:

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

打字稿代码:

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

整个打字稿文件:

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;
}

这是整个打字稿文件。

【问题讨论】:

  • 你能显示你所有的 TS 组件吗,因为 'jobExecutionList' 似乎不是 MatTableDataSource 类型
  • 您需要使用您的数组创建一个 matTableData 源: dataSource = new MatTableDataSource(jobExecutionList); (并将此数据源用作您的“数据源)
  • 如果错误仍然存​​在,请随时提供 Stackblitz
  • @BenThie 添加了我的 TS 组件文件。我如何制作 MatTableDataSource 类型的 jobExecutionList
  • @saad 我编辑我的答案

标签: javascript angular typescript angular-material


【解决方案1】:

根据不同的评论,你需要做:

dataSource: MatTableDataSource<any>;

然后当你得到数据时:

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

在你的例子中:

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();
  }

【讨论】:

    【解决方案2】:

    我已经有这个例子了,你可以看看这个。

    Mat-Table-stackblitz

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 1970-01-01
      • 2021-04-05
      • 2018-07-08
      • 2019-08-15
      • 2019-10-10
      • 2019-12-26
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多