角材料排序和分页器不起作用

时间:2019-12-11 09:14:40

标签: angular typescript angular-material

所以我在实现MatSort和MatPaginator时遇到问题。我遵循了官方角材料网站(https://material.angular.io/components/sort/overview)上的教程。但是,每次我尝试实现它时,它都不起作用。我的控制台日志中出现0个错误,所以我不知道我缺少什么。

messages.component.ts:

import { Component, OnInit, ViewChild, } from '@angular/core';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { MessagesService } from '../shared/services/messages.service';
import { IMessageCredentials } from '../shared/interfaces/messageCredentials.interface';
import { IMessage, IMessageData } from '../shared/interfaces/messages.interface';
import { IDriverData } from '../shared/interfaces/driver.interface';
import { DriverService } from '../shared/services/driver.service';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.scss']
})

export class MessagesComponent implements OnInit {  
  name: string = '';
  number: string = '';
  content: string = '';
  dataSource: MatTableDataSource<IMessageData>
  messagesData: IMessageData[];
  driverData: IDriverData[];

  displayedColumns: string[] = ['number', 'chauffeur' , 'executionDateTime', 'textDecoded', 'richting'];

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

  constructor(private messageService: MessagesService, private driverService: DriverService) { 
    this.getDrivers();
    this.dataSource = new MatTableDataSource(this.messagesData);
  }

  ngOnInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
    this.getMessages();
   }

  getMessages() {
    let credentials = <IMessageCredentials>{};
    credentials.login = "";
    credentials.password = "";
    credentials.unreadOnly = false;

    this.messageService.getAll(credentials).subscribe(response => {
      this.messagesData = response;
      this.dataSource = new MatTableDataSource(this.messagesData);
    })    
  }

  sendMessages() {
    let message = <IMessage>{};
    message.login = "";
    message.password = "";
    message.number = this.number;
    message.content = this.content;

    this.messageService.sendMessage(message).subscribe(response => {
      console.log("Send message: " + response)
    })

    window.alert("Send message to: " + this.number);
    this.content = "";
  }

  getDrivers() {
    let isAutoComplete: boolean = true;

    this.driverService.getDrivers(isAutoComplete).subscribe(response => {
      this.driverData = response;
    })
  }

  checkForDriverNames(phoneNumber: string) : string {
    let result = "";

    this.driverData.forEach(element => {      
      if (element.phone === phoneNumber){
        result = element.name;
      }
    });

    return result;
  }

  checkTraffic(folderNumber: string) : string {
    let result = parseInt(folderNumber) === 1 ? 'Ontvangen' : 'Verstuurd';

    return result;
  }
}

messages.component.html:

<div class="messages">
    <button mat-raised-button (click)="getMessages()">Refresh</button>

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

        <ng-container matColumnDef="number">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Telnr.</th>
            <td mat-cell *matCellDef="let row">{{row.number}}</td>
        </ng-container>

        <ng-container matColumnDef="chauffeur">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Chauffeur</th>
            <td mat-cell *matCellDef="let row">{{checkForDriverNames(row.number)}}</td>
        </ng-container>

        <ng-container matColumnDef="executionDateTime">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Timestamp</th>
            <td mat-cell *matCellDef="let row">{{row.executionDateTime}}</td>
        </ng-container>

        <ng-container matColumnDef="textDecoded">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>UserDataText</th>
            <td mat-cell *matCellDef="let row">{{row.textDecoded}}</td>
        </ng-container>

        <ng-container matColumnDef="richting">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Richting</th>
            <td mat-cell *matCellDef="let row">{{checkTraffic(row.folder)}}</td>
        </ng-container>

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

    <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
</div>

messages.module.ts:

import { NgModule } from '@angular/core';
import { MessagesComponent } from './messages.component';
import { BrowserModule } from '@angular/platform-browser';

import { SharedModule } from '../shared/shared.module';

import {
  MatSelectModule,
  MatCardModule,
  MatTableModule,
  MatCheckboxModule,
  MatPaginatorModule,
  MatSortModule
} from '@angular/material';

@NgModule({
  declarations: [
    MessagesComponent
  ],
  imports: [
    BrowserModule,
    SharedModule,
    MatCardModule,
    MatSelectModule,
    MatTableModule,
    MatCheckboxModule,
    MatPaginatorModule,
    MatSortModule
  ],
  exports: [
    MessagesComponent    
  ],
  providers: [],
  bootstrap: []
})
export class MessagesModule { }

3 个答案:

答案 0 :(得分:1)

此行:

this.dataSource = new MatTableDataSource(this.messagesData); 

它会覆盖分页器和排序(重置为null),因此请尝试如下操作:

this.messageService.getAll(credentials).subscribe(response => {
   this.messagesData = response;
   this.dataSource = new MatTableDataSource(this.messagesData);
   this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
});

答案 1 :(得分:1)

据我所知,这是asyncsync方法的问题。 试试这个:

ngOnInit(): void {
    this.messageService.getAll(credentials).subscribe(response => {
      this.messagesData = response;
      this.dataSource = new MatTableDataSource(this.messagesData);    
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
   }) 
}

答案 2 :(得分:0)

因为尚未填充messagesData,所以从构造函数中删除此行。

this.dataSource = new MatTableDataSource(this.messagesData);

另外将此行添加到您的ngInit

// If the user changes the sort order, reset back to the first page.
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);

我从不使用Angular material 8.x,但是,如果它不起作用,您可以尝试更改此行(这是我使用Angular material 7.x的方式)

this.dataSource = new MatTableDataSource(this.messagesData);

this.dataSource.data = new MatTableDataSource(this.messagesData);

完整代码(未经测试)

import { Component, OnInit, ViewChild, } from '@angular/core';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { MessagesService } from '../shared/services/messages.service';
import { IMessageCredentials } from '../shared/interfaces/messageCredentials.interface';
import { IMessage, IMessageData } from '../shared/interfaces/messages.interface';
import { IDriverData } from '../shared/interfaces/driver.interface';
import { DriverService } from '../shared/services/driver.service';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.scss']
})

export class MessagesComponent implements OnInit {  
  name: string = '';
  number: string = '';
  content: string = '';
  dataSource: MatTableDataSource<IMessageData>
  messagesData: IMessageData[];
  driverData: IDriverData[];

  displayedColumns: string[] = ['number', 'chauffeur' , 'executionDateTime', 'textDecoded', 'richting'];

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

  constructor(private messageService: MessagesService, private driverService: DriverService) { 
    this.getDrivers();
  }

  ngOnInit(): void {
    // If the user changes the sort order, reset back to the first page.
    this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
    this.getMessages();
   }

  getMessages() {
    let credentials = <IMessageCredentials>{};
    credentials.login = "";
    credentials.password = "";
    credentials.unreadOnly = false;

    this.messageService.getAll(credentials).subscribe(response => {
      this.messagesData = response;
      this.dataSource = new MatTableDataSource(this.messagesData);
    })    
  }

  sendMessages() {
    let message = <IMessage>{};
    message.login = "";
    message.password = "";
    message.number = this.number;
    message.content = this.content;

    this.messageService.sendMessage(message).subscribe(response => {
      console.log("Send message: " + response)
    })

    window.alert("Send message to: " + this.number);
    this.content = "";
  }

  getDrivers() {
    let isAutoComplete: boolean = true;

    this.driverService.getDrivers(isAutoComplete).subscribe(response => {
      this.driverData = response;
    })
  }