code

매트 테이블 정렬 데모가 작동하지 않음

starcafe 2023. 4. 28. 21:11
반응형

매트 테이블 정렬 데모가 작동하지 않음

나는 그것을 얻으려고 노력하고 있습니다.mat-table 로컬에서 작동하도록 정렬하고 데이터가 예상대로 표시되도록 할 수 있지만, 머리글 행을 클릭해도 온라인 예제에서와 같이 정렬되지 않습니다(아무 일도 일어나지 않음).이 데모를 현지에서 작동시키려고 합니다. https://material.angular.io/components/sort/overviewhttps ://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

Angular CLI를 사용하여 새 프로젝트를 생성한 후 다음 단계를 수행했습니다. https://material.angular.io/guide/getting-started

로컬 파일은 다음과 같습니다.

app.s.ts.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.component.vmdk

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <table-sorting-example></table-sorting-example>
</div>

테이블 위에 놓인 테이블 위에 놓인 의자들

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource" matSort>

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- ID Column -->
    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>


<!-- Copyright 2017 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->

테이블 위에 놓인 테이블 위에 놓인 의자들

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}


/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */

온라인 테이블처럼 나타나는데 정렬 기능이 부족한 이유에 대해 아는 사람이 있습니까?

이 문제가 발생할 수 있는 다른 사용자:문제는 각자재 웹사이트의 API 참조를 제대로 읽지 못했다는 것, 즉 MatSortModule을 Import해야 한다는 부분입니다.app.module.ts에서 가져오기 목록을 변경한 후

imports: [
    BrowserModule,
    MatTableModule,
    MatSortModule
  ],

그것은 잘 작동했습니다.

정렬 기능이 작동하는 문제가 있었는데 제대로 정렬되지 않았습니다.는 것을 깨달았습니다.matColumnDef 내소물이같합니다아야름이의의 .class / interface가 언가급고것은에서 것.matCellDef.

Angular Material 설명서에 따라 다음을 수행합니다.

기본적으로 MatTableDataSource는 정렬된 열의 이름이 열에 표시되는 데이터 속성 이름과 일치한다고 가정하여 정렬됩니다.

예를 들어:

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

name에 시대에matColumnDef는 지는다같합니다야아과와 같아야 .name에사용는에 <mat-cell>요소.

테이블이 내부에 있으면 *ngIf가 작동하지 않습니다.[숨김]으로 변경하면 작동합니다.

MatSort가 작동하지 않는 이유 중 하나는 데이터 소스(즉, 데이터 소스에 추가되는 경우)입니다.this.dataSource.sort = this.sort)을를) 을(를) 정의하기 전에 선택합니다.여러 가지 이유가 있을 수 있습니다.

  1. singOnInit에 . 않았기 에 ""를 수 있는 MatSort는 "MatSort"입니다.@ViewChild(MatSort, { static: true }) sort: MatSort;정의되지 않았으며 당연히 아무것도 하지 않을 것입니다.은 이동하는 것입니다.this.dataSource.sort = sorttongAfterViewInit입니다..이를 구성요소가 렌더링되는 것이라고 하며, MatSort를 정의해야 합니다.

  2. *ngIf를 사용하는 경우 테이블 요소에 템플릿이 있거나 상위 요소에 템플릿이 있는 경우 이 *ngIf를 사용하면 MatSort를 설정하려는 순간 테이블이 렌더링되지 않습니다.를 들어,이 있으면 신이만약.*ngIf="dataSource.data.length > 0" 요소에서 " " " " (데이터가 있는 경우에만 렌더링)"을 합니다.this.dataSource.sort = this.sort을 설정한 this.dataSource.data당신의 데이터와 함께.구성 요소 보기는 아직 렌더링되지 않으므로 MatSort는 여전히 정의되지 않습니다.

하려면 MatSort를 할 수 .*ngIf와 함께[hidden]다른 여러 답변에서 언급한 바와 같이.그러나 *ngIf 문을 유지하려면 다음 솔루션을 사용할 수 있습니다.이 솔루션은 Angular 9에서 작동합니다. 이전 버전에서 테스트를 해본 적이 없어서 작동하는지 잘 모르겠습니다.

여기서 이 솔루션을 찾았습니다. https://github.com/angular/components/issues/10205

다음을 넣는 대신:

@ViewChild(MatSort) sort: MatSort;

setter formatSort를 사용합니다.이 설정자는 보기에서 matSort가 변경되면(즉, 처음 정의된 경우) 실행되며 화살표를 클릭하여 정렬을 변경해도 실행되지 않습니다.다음과 같이 표시됩니다.

@ViewChild(MatSort) set matSort(sort: MatSort) {
    this.dataSource.sort = sort;
}

정렬을 (프로그래밍 방식으로) 변경하는 다른 기능이 있으면 다시 시작할지 확신할 수 없습니다. 아직 테스트하지 않았습니다.정렬이 정의되지 않은 경우에만 정렬이 설정되도록 하려면 다음과 같은 작업을 수행할 수 있습니다.

@ViewChild(MatSort) set matSort(sort: MatSort) {
    if (!this.dataSource.sort) {
        this.dataSource.sort = sort;
    }
}

matColumnDef 이름과 *matCellDef 실제 값 이름은 같아야 합니다.

예:

<ng-container matColumnDef="oppNo">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Opportunity Number</th>
    <td mat-cell *matCellDef="let element">{{element.oppNo}}</td>
</ng-container>

나의 경우 oppNo는 ColumnDef name과 *matCellDef name 및 sorting 형식이 동일합니다.

저도 이 문제에 부딪혔습니다. 하기 에, 아이가 정의될 때까지 를 구현하고 사용해야 .AfterViewInitInit에 없습니다.

  ngAfterViewInit (){
    this.dataSource.sort = this.sort;
  }

시간 초과 블록 내에 정렬을 추가하는 것은 나에게 효과가 있습니다.

dataSource = new MatTableDataSource(this.articleService.getAllArticles());
setTimeout(() => {
  this.tableDataSource.sort = this.sort;
  this.tableDataSource.paginator = this.paginator;
});

라이프사이클 훅을 사용하고 싶지 않은 경우.

저는 이 문제에 몇 시간을 소비했습니다.여러 스레드를 읽은 후에 다음과 같은 단계를 수행했습니다.

  1. @avern이 언급했듯이, 당신은 다음을 가져올 필요가 있습니다.MatSortModule.
  2. 테이블을 다음으로 둘러싸지 않도록 합니다.*ngIf로변으로 합니다.[hidden]@zerg의 권고대로.(왜 그런지 이해가 안가요)

이게 도움이 되길 바랍니다.

제 솔루션은 몇 가지를 수정하는 것이었습니다(기본적으로 이 페이지의 대부분의 솔루션을 병합).

확인할 사항:

  1. BrowserModule, MatTableModule, MatSortModule모듈을 루트 모듈 파일로 가져와야 합니다.
  2. 사용했는지 확인하십시오.MatTableDatasource 합니다.
  3. 테이블이 다음에 중첩되지 않았는지 확인합니다.*ngIf=....대신 할 수 없음).대신 다른 조건부 연산을 사용합니다(이유는 여전히 이해할 수 없음).

app.sys.ts에서 다음을 수행합니다.

수입품

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

그 다음에 추가

imports: [
    ...
    MatSortModule
],

시나리오에서 테이블 데이터의 이름을 *matColumnDef와 동일하게 지정하여 이 문제를 해결했습니다. 예:

<!-- Name Column -->
<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
  <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
</ng-container>

대신

<!-- Name Column -->
    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

몇 주 동안 이 일에 시간을 보낸 후에.나는 당신을 다음과 같이 알게 되었습니다.

  1. app.module.ts에서 MatSortModule을 가져와야 합니다.
 imports: [
    ...
    MatSortModule
],
<ng-container matColumnDef="ledgerTransactionCreditSum">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Ledger Transaction Credit </th>
        <td mat-cell *matCellDef="let element"> {{element.ledgerTransactionCreditSum}} </td>
    </ng-container>
 matColumnDef and element.ledgerTransactionCreditSum variable and matcolumn def shoulde be same
  1. ningView에서 정렬 및 페이지 관리자 정의Init
ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.dataSource.paginator?._changePageSize(400)
  }

저에게는 두 가지 문제가 있었습니다.

  1. matColumnDef와 matCellDef -> 이름이 다릅니다.
  2. 저는 서비스에서 데이터를 얻고 있었습니다.ngOnInit 정렬이 작동하지 않습니다.대체됨

    ngAfterViewInit() {this.dataSource.sort = 이것.정렬; }

저는 이 오래된 블로그를 발견했고, 이 블로그를 사용할 수 있게 되었습니다.

  1. 를 반드시 해 주세요.MatSortModule
  2. 다음을 지정합니다.matSort
  3. 데이터 소스를 다음과 같이 포장해야 합니다.MatTableDataSource
    • 이것이 제가 그것을 정리하는 데 도움을 준 입니다.템플릿에서 어레이를 직접 참조했습니다(<table mat-table [dataSource]="this.products" matSort>.<table mat-table [dataSource]="this.dataSource" matSort>) )와 데이터 소스가 dataSource = new MatTableDataSource(this.products)
  4. 정렬에 .ngOnInit/ngAfterViewInit
  5. 사용하지 않으려면 자신의 정렬을 작성합니다.MatTableDataSource

이 이름들이 동일해야 하는 것에 대해 혼란스러워하는 사람들을 위해, 저는 몇 가지 테스트를 했습니다.

이렇게 하면 작동합니다(속성 이름이 열 정의와 동일).

<ng-container matColumnDef="version">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Version </th>
    <td mat-cell *matCellDef="let element"> {{element.version}} </td>
</ng-container>

displayedColumns: string[] = ['version']

이렇게 하면 작동하지 않습니다(속성 이름이 열 정의와 동일하지 않음).

<ng-container matColumnDef="version2">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Version </th>
    <td mat-cell *matCellDef="let element"> {{element.version}} </td>
</ng-container>

displayedColumns: string[] = ['version2']

참고로, 이것도 작동하지 않습니다(속성의 길이).

<ng-container matColumnDef="length">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Version </th>
    <td mat-cell *matCellDef="let element"> {{element.ids.length}} </td>
</ng-container>

displayedColumns: string[] = ['length']

이 또한 마찬가지입니다.

<ng-container matColumnDef="ids.length">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Version </th>
    <td mat-cell *matCellDef="let element"> {{element.ids.length}} </td>
</ng-container>

displayedColumns: string[] = ['ids.length']

매트 소트 & 매트 페이지네이터가 작동하지 않는 주요 이유는

  1. MatSortModule 및 MatPaginatorModule 모듈을 가져오지 않았습니다.
  2. 테이블이 *ngIf 조건에 있습니다.
  3. matColumnDef는 matCellDef 및 표시된 Columns 배열과 같아야 합니다.

저는 *ngIf를 mat-table 태그의 [hidden] 특성으로 대체했습니다.Angular Material 커뮤니티에 버그로 게시하는 방법은 무엇입니까?

아래 코드는 저에게 완벽하게 적용되었습니다.

@ViewChild(MatSort) set matSort(sort: MatSort) {
if (!this.dataSource.sort) {this.dataSource.sort = sort;}}

여러분의 안에 것과 이 있다고 한다면, 의 테이블을 하세요.sortingDataAccessor함수는 나에게 그랬던 것처럼 문제를 해결할 수도 있습니다.나는 내 테이블을 몇 개의 *ngIfs 안에 두고 그 *ngIfs에서 그것을 꺼내면 말이는 말이 안 됩니다.

`ngAfterViewInit(): void {
        this.matchesDataSource.sort = this.sort;
        this.matchesDataSource.sortingDataAccessor = previewMatchSortingFn;
    }`

`export function previewMatchSortingFn(item: Match, header: string): string | number {
    switch (header) {
        case 'home':
            return item.homeTeam.name;
        case 'away':
            return item.awayTeam.name;
        case 'date':
            if (item.dateTime) {
                // this will return the number representation of the date
                return item.dateTime.valueOf();
            }
            return;
        default:
            break;
    }
}`

저는 이 질문에 대한 답을 여러 개 찾았지만, 개별적으로 실행해도 아무런 결과를 얻지 못했습니다.그래서 저는 답을 병합하려고 노력했고 효과가 있었습니다.

먼저, 나는 NgAfterView 안에 ViewChild sort를 추가했습니다.Init 인터페이스.(처음에는 NgOnInit를 통해 호출된 함수 안에 있었습니다.

 ngAfterViewInit(){
    this.tableData.sort = this.sort;
  }

두 번째 단계에서는 컨테이너 내부의 *ngIf를 [숨김]으로 변경했습니다.값이 로드되지 않았다는 오류가 발생합니다.하지만 그것은 지금까지 걱정할 만한 중요한 것은 아닙니다.

전에

<div class="mat-elevation-z0 container-fluid" *ngIf={some boolean resultant condition}>

끝나고

<div class="mat-elevation-z0 container-fluid" [hidden] = {negation of your boolean expression}>

psst.. 테이블이 매트 푸터를 통해 위의 bs 위로 로드되는 동안 로드 스피너를 추가하는 것도 고려할 수 있습니다.

    <ng-container matColumnDef="loading">
                    <mat-footer-cell *matFooterCellDef colspan=6>
                        <div class="uploader-status">
                            <mat-spinner strokeWidth="25" [diameter]="100" title="Server Starting" ></mat-spinner>
                        </div>
                    </mat-footer-cell>
</ng-container>


<mat-footer-row *matFooterRowDef="['loading']" [ngStyle]="{'display': (this.candidateService.candidateRecords!=null) ? 'none':'block'}"></mat-footer-row>

만약 당신이 여기까지 모든 답을 읽었지만 아무것도 도움이 되지 않는다면, 아마도 당신은 나와 같은 문제를 가지고 있을 것입니다.

는 저의 문제나입니다.MatTableDataSource

dataSource = new MatTableDataSource<StbElement>(ELEMENT_DATA);

없이 파일에서 되었습니다.this.

변경:

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

받는 사람:

<table mat-table [dataSource]="this.dataSource" matSort class="mat-elevation-z8">

문제를 해결했습니다.

이전의 모든 답변 외에도 데이터를 검색할 때 표가 보이지 않는 경우가 있습니다.예를 들어, 모달/대화 상자 안에 MatSort 및 MatPaginator가 있는 표를 표시해야 했습니다.따라서 다음과 같은 각 출력 이미터 기능을 통해 요소를 전달해야 했습니다.

<... matSort #sort="matSort" (matSortChange)="sortData(sort)">
<... #paginator (page)="changePaginator(paginator)">

타이프스크립트에는 다음과 같은 것들이 있습니다.

  @ViewChild(MatSort, { static: false }) set sort(s: MatSort) {
      this.dataSource.sort = s;
  }
  @ViewChild(MatPaginator, { static: false }) set paginator(p: MatPaginator) {
      this.dataSource.paginator = p;
  }

  sortData(sort: MatSort) {
      this.sort = sort;
  }
  changePaginator(paginator: MatPaginator) {
      this.paginator = paginator;
  }

후 에 입력 . 위 코 드 는 페 요 설 때 입 지 에 페 에 어 의 합 자 야 설 해 다 니 정 기 을 값 본 징 이 의 문 서 하 시 력 기[pageSize]="5" [length]="dataSource?.data?.length"이것을 이전의 모든 솔루션에 대한 마지막 수단으로 사용하십시오.

나한테 효과가 있어요..

@ViewChild('sortConfigTable', { static: false }) sortConfigTable: MatSort;

데이터 초기 할당 후

      this.dataSource.data = ds;

      setTimeout(() => {
        if (this.sortConfigTable) {
          this.dataSource.sort = this.sortConfigTable;
        }
      }, 1000);

실제로 matColumnDef 이름(즉, 열 이름)과 클래스/인터페이스 속성 이름이 같아야 작동합니다.

클래스/인터페이스 속성 이름을 변경할 수 없는 경우가 있는데, 이 경우 아래와 같이 사용자 지정 정렬을 구현할 수 있습니다.

let say your columns  as  ['id', 'name'] and 
your class/interface  as  ['userId', 'name']

'id' 열에서 정렬을 수행하면 작동하지 않습니다.사용자 지정 정렬 사용

this.dataSource.sortingDataAccessor = (item,property)=>{

 // where item is your class/interface data
 // where property is your column name

       switch(property){
           case 'id' : return item.userId
           default: return item[property];
        }
}
My solution for this problem is as below - 


1. These two lines will go in the same order.

    this.dataSource = new MatTableDataSource(myRowDataArray);// this dataSource is used in table tag.
    this.dataSource.sort = this.sort;


2. Pass MatTableDataSource object in [dataSource] 
    <table mat-table [dataSource]="dataSource">
    // rest of the table definition here
    </table>

3. By default, the MatTableDataSource sorts with the assumption that the sorted column's name matches the data property name that the column displays.

Example - 
    <ng-container matColumnDef="date" >
          <th class="headers" mat-header-cell  *matHeaderCellDef mat-sort-header>Date</th>
          <td class="data" mat-cell *matCellDef="let row">{{row.date|date}}</td>
    </ng-container>

4. If the table is inside *ngIf,then replace it with [hidden] or some other filter.

두 번째 포인트를 놓쳤습니다.

Cheers!

이 문제는 주로 다음과 같은 경우에 발생합니다.sort는 다이에초니다됩기화전 됩니다.dataSource여기서 찾은 데모에서dataSource이 정적으로 초기화되므로 문제가 발생하지 않습니다.할 호출에 될 때까지 .dataSource초화하전에를 sort인스턴스 변수입니다.

이유는 모르겠지만 퍼팅.this.dataSource.sort = this.sort;의에할에 ngAfterViewInit()방법이 작동하지 않았습니다.나도 이 기능이 페이지 로드가 안 된 후에도 계속 작동하고 있다는 것을 확인했습니다.저의 해결책은 정렬 과제를 넣는 것이었습니다.ngOnInit()방법.

 ngOnInit(): void {
   this.service.getAllAudits().subscribe(result => { 
    this.dataSource  = new MatTableDataSource(result); 
    this.dataSource.sort = this.sort; 
  });

}

변화하는

@ViewChild('matsort') sort: MatSort;

로.

@ViewChild(matSort) sort: MatSort

나를 위해 그것을 한 것은 동일해야 합니다.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort matSortActive="name" matSortDirection="asc">

dataSource를 할당할 때 사용합니다.sort = this.message, 이 줄은 ngAfterView 내부에 유지해야 합니다.ngOnInit 내부가 아닌 Init.

저도 같은 문제가 있었습니다.제가 위에서 작업을 하자 잘 작동하기 시작했습니다.

그 이면에는 몇 가지 이유가 있을 수 있습니다. 설명서를 올바르게 따르고 필요한 모든 모듈을 가져오십시오. 그러나 오류가 계속 발생할 경우 다음과 같은 이유가 있을 수 있습니다.

  1. 테이블에는 matSort 지시어를 추가하고 셀에는 mat-Sort-header 지시어를 추가해야 합니다.

  2. 테이블이 *ngIf에 있으면 정렬 및 페이지 표시도 작동하지 않습니다.

      <table mat-table [dataSource]="dataSource" matSort (matSortChange)="announceSortChange($event)">
      <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by No">
    

언급URL : https://stackoverflow.com/questions/46893164/mat-table-sorting-demo-not-working

반응형