【问题标题】:Using MatSort of Angular Material使用 MatSort 的 Angular 材质
【发布时间】:2022-01-09 22:49:13
【问题描述】:

我的 customer.component.ts 中有这个:

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { NorthwindService } from 'swagger';
import {LiveAnnouncer} from '@angular/cdk/a11y';
import {MatSort} from '@angular/material/sort';

@Component({
  selector: 'app-customers',
  templateUrl: './customers.component.html',
  styleUrls: ['./customers.component.scss']
})
export class CustomersComponent implements OnInit {

  displayedColumns: string[] = ['id', 'name', 'contact', 'city', 'country', 'orders'];
  customers!: any[];

  constructor(private northwindService: NorthwindService, private _liveAnnouncer: LiveAnnouncer) { }

  @ViewChild(MatSort) sort!: MatSort;


  ngOnInit(): void {
    
    this.northwindService.apiCustomersGet().subscribe(data => {
       this.customers = data;
    });
     this.customers.sort = this.sort; <--- this wont't compile
  }
}

this.customer.sort = this.sort; 出现了一些问题。

Iget 的错误是:

类型 'MatSort' 不能分配给类型 '(compareFn?: ((a: any, b: any) => number) | undefined) => any[]'。 类型 'MatSort' 不匹配签名 '(compareFn?: ((a: any, b: any) => number) | undefined): any[]'.ts(2322)

我看到的关于它的每个教程都有效。

【问题讨论】:

    标签: angular angular-material material-design angular8


    【解决方案1】:

    docs example所示:

    @ViewChild(MatSort, {static: true}) sort: MatSort;
    
    ...
    this.dataSource = new MatTableDataSource(yourData);
    this.dataSource.sort = this.sort;
    
    

    【讨论】:

      【解决方案2】:
      1. 首先,最好不要在排序时使用“Any[]”,而是必须 定义客户模型结构并使其可读 编译器。
      2. 注意MatSort需要添加到MatTableDataSource,
      3. 在视图初始化之后设置排序,因为该组件将能够使用 ngAfterViewInit() 查询其视图的初始化排序

          import { MatTableDataSource } from '@angular/material/table';
          import { AfterViewInit, ViewChild } from '@angular/core';
              
          export class CustomersComponent implements OnInit, AfterViewInit {
          displayedColumns: string[] = ['id', 'name', 'contact', 'city', 'country', 'orders'];
          customers: Customer[] = CustomerMock; //Define and initialize the structure
          dataSource = new MatTableDataSource<Customer>( this.customers );
          @ViewChild( MatSort ) sort: MatSort;
              
          ngAfterViewInit() {
            this.dataSource.sort = this.sort;
          }

      模板中需要在 mat-table 中注入“数据源”变量

            &lt;table mat-table [dataSource]="dataSource" matSort &gt;

      【讨论】:

        猜你喜欢
        • 2021-10-07
        • 2018-06-17
        • 2016-11-10
        • 1970-01-01
        • 2018-02-16
        • 1970-01-01
        • 2017-01-25
        • 2017-04-06
        • 2019-03-07
        相关资源
        最近更新 更多