网站搜索

typescript - Angular 方法用于填充强类型变量


我刚接触 Angular,对此有些挣扎。如果我的措辞不够准确,抱歉;希望你能理解我的意思。

我有一些带有点击事件的 HTML,这个事件会返回所选的数据行。我想填充一个基于我创建的模型的变量。点击事件返回数据没有问题:当我记录返回值时,我在控制台中看到了所选的数据。模型也没有问题,我在其他地方以不同方式使用过。我的问题是,在这种情况下,该变量是一个强类型数组,我似乎无法成功将行数据分配给这个数组。

这是我如何定义这个变量的:

public selectedItem: thisModel[];

这是我尝试将选定行的值赋给 selectedItem 变量的最新方法版本:

getItemInfo(row: any[]){
      this.selectedItem =[];
      var selectedRow = row[0];
      this.selectedItem[0].Description= selectedRow.Description;
      this.selectedItem[0].StartDate= selectedRow.StartDate;
      this.selectedItem[0].EndDate= selectedRow.EndDate;
  }

为了万无一失,这里是模型,我已经将其导入到组件中:

export class thisModel {

    UnitCode: number;
    Description: string;
    StartDate: Date;
    EndDate?: Date;

}

不幸的是,控制台错误显示:无法设置未定义的 Description 属性,而不是将所选行的值分配给变量。

正如我之前所说,我尝试了这个方法的许多不同版本,结果都是一样的。我哪里出错了?

感谢所有回答的人。

答案#1

在设置值之前,你需要检查 null 和 undefined,并使用 push 方法将对象插入到 selectedItem 数组中

getItemInfo(row: any[]){
      this.selectedItem =[];
      var selectedRow = row[0];
      if (selectedRow != null && selectedRow != undefined){
        this.selectedItem.push(
        { 
         Description: selectedRow.Description,
         StartDate: selectedRow.StartDate,
         EndDate: selectedRow.EndDate
        });
      }
  }