【问题标题】:iterating interface array using *ngFor in typescript在 typescript 中使用 *ngFor 迭代接口数组
【发布时间】:2020-03-30 05:10:39
【问题描述】:

所以我已经实现了一个用于从服务类中检索数据的接口。

export interface FilteredSubjects {
  key: string,
  list: Subject[]
}

所以目前我想迭代FilteredSubject 接口数组。所以我检查使用console.log

console log output

但我无法使用 *ngFor 对其进行迭代。 这是我到目前为止所尝试的。这里selectedStreamList值显示在界面Key属性中

html

<mat-step [stepControl]="firstFormGroup" *ngFor="let stream of selectedStreamList; let indexOfelement = index;">
<div class="class=pl-5">
  <table class="table table-borderless ">
    <tbody>

    <ng-container *ngFor="let subject of getStreamFilter(indexOfelement)">
      <tr>
        <th scope="row">  <mat-checkbox  (change)="toggle(subject)"> {{subject.name}} </mat-checkbox></th>
        <td><a (click)="openDeleteSubjectDialog(subject.id)">
          <mat-icon class="aligned-with-icon" color="warn">delete</mat-icon>
        </a></td>
      </tr>

    </ng-container>
  .....

这个Ts方法。我正在从父组件获取过滤列表。

 @Input("slist") filteredlist: FilteredSubjects[];



 constructor() {
  }

  ngOnInit() {}


getStreamFilter(index:number) : Subject[]{
    return this.filteredlist[index].list;
}

但这不起作用。如何解决这个问题?

这是错误

【问题讨论】:

  • 你在哪里初始化filteredlist,它是未定义的,所以filteredlist[index] 将是未定义的,从而导致ngFor终止
  • 我是从父组件那里得到的。我已经更新了这个问题:)
  • @PasinduSenarath 你能用 Stackblitz 中的 simple 示例重新创建 问题 吗?
  • 你是如何从父级传递输入属性的:如果你像这样传递输入 [slist]="x" 其中 x 是值列表。它应该工作

标签: angular typescript interface ngfor


【解决方案1】:

经过一番研究,我找到了解决这个问题的方法。是调用方法的问题。

 getStreamFilterX(index:number) : Subject[]{

this.selectedStreamID = index;
let subList: Subject[] = [];
this.filteredlist.forEach((item: FilteredSubjects) => {
  if(item.key == index.toString()) {
    subList = item.list;
  }
});
return subList;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2018-08-31
    • 1970-01-01
    • 2016-11-28
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多