簡體   English   中英

Angular 材料台墊排序不工作

[英]Angular Material table matSort not working

我的桌子有問題

我獲取數據,然后將其傳遞給我的表

這是我的代碼:

html

<div class="mainContainer">
  <div class="mat-elevation-z8 content">

  <mat-table
    class="mat-elevation-z3 productsTable"
    matSort
    mat-table
    [dataSource]="productsDataForTable">

    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Title
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        {{row.name.en}}
      </mat-cell>
    </ng-container>

  <ng-container matColumnDef="image">
      <mat-header-cell *matHeaderCellDef>
        Image
      </mat-header-cell>
      <mat-cell *matCellDef="let prod; let i = index" >
        <img class="prodThumbnail" src={{prodsThumbnails[i]}} alt="Product thumbnail">
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Description
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.description.en}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Weight
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.weight + ' ' + prod.weightUnit}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="SKU">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        SKU
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.sku}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="price">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Price
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        $ {{prod.prices[0].unitPrice}} {{prod.prices[0].currency}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Category
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.category}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Status
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.status}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
        Actions
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        <mat-icon class="actionOnProductButton" (click)="openProductDetailsDialog(prod)">create</mat-icon>
        <mat-icon class="actionOnProductButton" (click)="openDeleteProductDialog(prod)">delete</mat-icon>
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="tableHeaders"></mat-header-row>
    <mat-row
      class="table-rows"
      *matRowDef="let row; columns: tableHeaders;">

    </mat-row>


  </mat-table>

  </div>
</div>

TS

import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Catalog } from '../../catalog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ProductsService } from '../../products.service';
import { EnvironmentConfigService } from 'src/app/manufacturer/environment-config.service';

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

  catalogID: string;
  productsFetched: any;

  // For product thumbnail in table 
  prodsThumbnails = [];

  // Data for products table
  productsDataForTable: MatTableDataSource<[]>;
  tableHeaders = [
    'image',
    'title',
    'description',
    'weight',
    'SKU',
    'price',
    'category',
    'status',
    'actions'
  ];

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

  constructor(
    private envService: EnvironmentConfigService,
    private prodsService: ProductsService,
    private snackBar: MatSnackBar,
    public dialog: MatDialog,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private catService: CatalogsService
  ) { }

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      this.getProducts(params.id);
    });
  }

  getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
      this.productsDataForTable = new MatTableDataSource(prods);
      this.productsDataForTable.sort = this.sort;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
  }

}

該表帶有*ngIf並且我讀到 matTable 不應該有它,因為@ViewChild(MatSort, {static: true}) sort: MatSort將是未定義的,所以我刪除了我實際使用的*ngIf但我仍然無法實現排序。

我也嘗試了 matPagination 功能但沒有成功,我想這是由於同樣的錯誤。

我會很感激任何幫助

請嘗試將 MatSortModule 添加到您的模塊中。

import {MatSortModule} from '@angular/material/sort';


imports: [
    BrowserModule,
    ...
    MatTableModule,
    MatSortModule
],

嘗試這個:

 ngAfterViewInit() {
      this.productsDataForTable = new MatTableDataSource(this.productsFetched);
      this.productsDataForTable.sort = this.sort;
  }


    getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

我發現出了什么問題:

您在 matColumnDef 中定義的內容實際上應該與將在每一行上顯示的對象的 object 屬性相匹配。

所以我確實在將數據傳遞到表之前填充了我的對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM