【问题标题】:Property 'sort' has no initializer and is not definitely assigned in the constructor属性“排序”没有初始值设定项,也没有在构造函数中明确分配
【发布时间】:2021-08-30 11:48:57
【问题描述】:

我正在尝试使用 MatSort 模块在 Angular Material 中对我的表格进行排序,但出现此错误:

Property 'sort' has no initializer and is not definitely assigned in the constructor.

这是我的 ts 文件:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Personal } from 'src/app/models/personal.model';
import { PersonalService } from 'src/app/services/personal.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator'; 
import { MatSort, MatSortModule, MatSortHeader } from '@angular/material/sort'

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

export class PersonalListComponent implements OnInit {
  personals?: Personal[];
  currentPersonal?: Personal;
  currentIndex = -1;
  name = '';

  PERSONAL_DATA : Personal[] = []
  displayedColumns: string[] = ['name', 'action'];
  dataSource = new MatTableDataSource<Personal>(this.PERSONAL_DATA);
  
  @ViewChild(MatSort) sort: MatSort;

  constructor(private personalService: PersonalService) { }

  ngOnInit(): void {
    this.getAllPersonalTable();
  }

  private getAllPersonalTable(){
    let resp = this.personalService.getAllPersonal();
    resp.subscribe(report =>this.dataSource.data=report as Personal[]);
    this.dataSource.sort = this.sort;
  }

}

此行出现错误

@ViewChild(MatSort) sort: MatSort;

是的,我试过sort!。这消除了错误,但无法编译我的页面。 "strictPropertyInitialization": false,在 tsconfig.json 文件中也是如此。

非常感谢任何有关如何解决的帮助!!!

【问题讨论】:

  • 不应该在 app.module 中导入模块 MatSortModule、MatPaginatorModule 吗?
  • @SanjayChoudhary 我有一个personal.module.ts 文件,我在其中导入了所有模块,我也在app.module.ts 文件中导入了这些模块
  • 那你为什么在 app.component 文件中有这些模块呢?你应该检查 tsconfig 中所有说严格的属性。
  • @SanjayChoudhary 因为我必须在 app.module.ts 文件中导入 module.ts 文件。它基本上是共享模块-另外,我认为您混淆了 app.component 和 app.module 文件

标签: angular angular-material


【解决方案1】:

我遇到的问题和你一模一样。这是因为 Angular 12 在 typescript 中启用了严格模式(参考 here)。

尝试:

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

【讨论】:

  • !解决了我的问题,这是否意味着可以为空?
【解决方案2】:

试试这个;

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

【讨论】:

    【解决方案3】:

    如果您使用的是最新版本的 Angular,请使用

     @ViewChild(MatSort) sort = new MatSort();
    

    基本上是打字稿编译器错误。

    在新版本中,typescript 引入了 strick 类 Initialization。

    在 Angular 12 或更高版本中,您可能会遇到此问题。

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 1970-01-01
      • 2021-04-09
      • 2021-07-10
      相关资源
      最近更新 更多