【问题标题】:Material angular table with dynamic data具有动态数据的材料角表
【发布时间】:2021-08-12 18:15:59
【问题描述】:

我是 Angular 新手,我正在尝试制作一个动态表格来显示数据。

是的,我有它(有点工作)静态数据。

我从这个例子中得到启发:https://stackblitz.com/angular/lrpjroljdly?embed=1&file=app/table-selection-example.html

const COLUMN_DATA: IClusterColumnOrient[] = [...Array(10).keys()].map((_, index) =>({
      columnName: (Math.random() + 1).toString(36).substring(7),
      schemaName: (Math.random() + 1).toString(36).substring(7),
      columnType: (Math.random() + 1).toString(36).substring(7),
      id: (Math.random() + 1).toString(36).substring(7),
      tableName: (Math.random() + 1).toString(36).substring(7),
      databaseName: (Math.random() + 1).toString(36).substring(7),
      databaseId: (Math.random() + 1).toString(36).substring(7)
}))




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


export class ColumnSearchComponent implements OnInit{

  displayedColumns: string[] = ['select', 'columnName', 'columnType', 'tableName', 'schemaName'];

  selection = new SelectionModel<IClusterColumnOrient>(true, []);
  @ViewChild('searchInput', { static: true }) searchInput: ElementRef;
  columnsData: IClusterColumnOrient[]
  isSearching: boolean 
  columns: string[]
  dataSource = new MatTableDataSource<IClusterColumnOrient>(COLUMN_DATA);

这很好用,但是当我想使用动态数据时,我会初始化一个空数组,以及用户输入什么来动态查询我的后端。


  constructor(private httpClient: HttpClient){
    this.isSearching = false
    this.columnsData = []
    //Hardcoded as of now, we can import and parse from backend in the future
  }
  
  ngOnInit(){
    console.log(this.columnsData)
    fromEvent(this.searchInput.nativeElement, 'keyup').pipe(
      //Find type for js event
      map((event: any) =>{
        return event.target.value
      }),
      debounceTime(700),
      distinctUntilChanged(),
      .....

当我尝试将 COLUMN_DATA 替换为 this.columnData 时,我收到如下错误:

Property 'columnsData' is used before its initialization.

如何用动态数据替换它?

【问题讨论】:

  • 请为您的代码的第二个版本创建 stackblitz 示例。
  • 不是在构造函数中赋值,而是在变量声明时赋值,即columnsData: IClusterColumnOrient[] = [];。我假设错误来自 TSlint、ESlint 或类似的东西,这确保您不使用未初始化的属性。代码,如果编译,将正常工作,但严格的检查确保你不会犯任何错误。您可能可以在 linting 选项中的某处禁用它。

标签: angular typescript


【解决方案1】:

错误消息在这里揭示了一个重要线索。您只声明属性columnsData: IClusterColumnOrient[] 而不对其进行初始化。您在 constructor 中处理此变量的初始化,但在您创建 MatTableDataSource 时,它仍未初始化,仅声明。您只能像使用 columnsData 属性一样声明数据源

dataSource: MatTableDataSource<IClusterColumnOrient>;

然后将你的数据源初始化也移动到构造函数中以避免这个问题。

constructor(private httpClient: HttpClient){
    this.isSearching = false
    this.columnsData = []
    this.dataSource = new MatTableDataSource<IClusterColumnOrient>(this.columnsData);
  }

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2020-12-17
    • 2021-09-03
    • 1970-01-01
    • 2018-09-26
    • 2020-11-19
    • 2019-05-14
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多