我的 mat-table 工作正常,但是在按照官方 api 文档添加 mat-sort 时,它在 ngAfterViewInit 失败并显示以下消息
错误类型错误:无法设置未定义的属性“排序”
数据从 api 正确显示,我将代码移动到组件的构造函数中,仅在 onInit 中设置: this.listData.sort = this.sort;
我在 app.module 中导入了模块。
所以这是我的 3 个文件:
组件网.html
<mat-table [dataSource]="listData" matSort>
<ng-container matColumnDef="gender">
<mat-header-cell *matHeaderCellDef mat-sort-header>Gender</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.gender}}</mat-cell>
</ng-container>
<ng-container matColumnDef="firstname">
<mat-header-cell *matHeaderCellDef mat-sort-header>First Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.firstname}}</mat-cell>
</ng-container>
组件.ts
import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {PersonneService} from '../../shared/personne.service';
import { MatTableDataSource, MatSort} from '@angular/material';
import {Personne} from '../../personne';
@Component({
selector: 'app-personne-list',
templateUrl: './personne-list.component.html',
styleUrls: ['./personne-list.component.css']
})
export class PersonneListComponent implements AfterViewInit {
personne: any = [];
constructor(private service: PersonneService) {
this.service.getPersonnes().subscribe((data: {}) => {
this.personne = data;
this.listData = new MatTableDataSource(this.personne);
});
}
listData: MatTableDataSource<Personne>;
displayedColumns: string[] = ['gender', 'firstname', 'lastname', 'address', 'city', 'state', 'ordertotal', 'actions'];
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
console.log({SORT: this.sort});
this.listData.sort = this.sort;
}
}
服务.ts:
import { Injectable } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {Personne} from '../personne';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PersonneService {
constructor(private http: HttpClient) { }
form: FormGroup = new FormGroup({
firstname: new FormControl('', Validators.required),
lastname: new FormControl('', Validators.required),
address: new FormControl('', [Validators.minLength(8), Validators.required]),
city: new FormControl(''),
state: new FormControl(''),
gender: new FormControl('1'),
ordertotal: new FormControl('')
});
endpointGet = 'http://localhost:3000/api/personnes';
endpointPost = 'http://localhost:3000/api/personne/';
getPersonnes() {
return this.http.get(this.endpointGet);
}
当我写这个问题时,我找到了这个答案: https ://stackoverflow.com/a/53112864/11295075
我将此添加到 html 中: [hidden]="!listData.data" matSort
它变成了:<mat-table [dataSource]="listData" [hidden]="!listData.data" matSort>
现在,当我单击它时排序但不正确,这是控制台中的错误: 错误类型错误:无法读取未定义的属性“数据”
感谢您的帮助。