Angular 7: 使用来自服务的数据对Mat-Table进行排序,作为MatTableDataSource
创始人
2024-10-16 22:31:53
0

以下是使用Angular 7对Mat-Table进行排序的示例代码:

  1. 创建一个名为DataService的服务来获取数据:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  getData() {
    // 返回一个Observable,用于模拟异步获取数据
    return of([
      { name: 'John', age: 30 },
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 40 }
    ]).pipe(delay(1000)); // 添加延迟以模拟异步请求
  }
}
  1. 在组件中使用MatTableDataSourceMatSort来排序表格数据:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { DataService } from './data.service';

@Component({
  selector: 'app-my-table',
  templateUrl: './my-table.component.html',
  styleUrls: ['./my-table.component.css']
})
export class MyTableComponent implements OnInit {
  dataSource: MatTableDataSource;
  displayedColumns: string[] = ['name', 'age'];

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.dataSource = new MatTableDataSource(data);
      this.dataSource.sort = this.sort;
    });
  }
}
  1. 在组件的HTML模板中使用MatTableMatSortHeader来呈现和处理排序:

    
    
Name {{element.name}} Age {{element.age}}

通过这些代码,你可以在Angular 7中使用来自服务的数据对Mat-Table进行排序。

相关内容

热门资讯

透视普及!德普之星辅助器怎么用... 透视普及!德普之星辅助器怎么用(透视)wepokerplus辅助,教程积累(有挂透视)-哔哩哔哩1、...
hhpoker有没有辅助!德扑... hhpoker有没有辅助!德扑HHpoker有挂吗(透视)软件-果然总结存在有挂1、进入游戏-大厅左...
hhpoker透视码怎么用!约... hhpoker透视码怎么用!约局吧开挂(透视)器-一贯揭幕有挂1、超多福利:超高返利,海量正版游戏,...
透视了解!wejoker开挂(... 透视了解!wejoker开挂(透视)wpk真的有透视嘛,教程窍门(有挂方式)-哔哩哔哩1、wpk真的...
wejoker黑侠辅助器!we... wejoker黑侠辅助器!wepoker-h5下载(透视)app-确实透视真的是有挂1、超多福利:超...
透视必备!hhpoker买挂(... 透视必备!hhpoker买挂(透视)aapoker免费透视脚本,教程秘籍(有挂工具)-哔哩哔哩1、a...
哈糖大菠萝有挂吗!hhpoke... 哈糖大菠萝有挂吗!hhpoker万能辅助器(透视)技巧-确实必备存在有挂1、不需要AI权限,帮助你快...
透视开挂!aapoker辅助器... 透视开挂!aapoker辅助器是真的吗(透视)聚星ai辅助工具下载,教程机巧(有挂细节)-哔哩哔哩运...
wepoker有没有插件!hh... wepoker有没有插件!hhpoker开挂靠谱吗(透视)工具-原来总结真的是有挂1、hhpoker...
透视了解!wepoker透视脚... 透视了解!wepoker透视脚本免费下载(透视)wepoker一直输的号能继续打吗,教程项目(了解有...