【问题标题】:Angular ngFor using a MapAngular ngFor 使用地图
【发布时间】:2023-04-11 11:42:01
【问题描述】:

我使用的是 ionic 3,因此是 angular 和 typescript。

我想要实现的是将 ngFor 与 Map 类型一起使用。

这是我所拥有的:

interface IShared_Position {
lat: number;
lng: number;
time: number;
color?: string;
}
public shared_position = new Map<string, IShared_Position>();

现在从 html 方面我有:

    <ion-list>
  <ion-item ion-item *ngFor="let item of shared_position">
    <h2>{{ item.time }}</h2>
  </ion-item>

现在这给了我以下错误:

错误:找不到“object”类型的不同支持对象“[object Map]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

现在有什么可能的方法我不能绑定我的地图,即使它不可迭代?

我该怎么办?

【问题讨论】:

    标签: angular typescript ngfor iterable


    【解决方案1】:

    如果你只需要这些值,你可以遍历那些

    html:

    <ion-item ion-item *ngFor="let item of getValues()">
        <h2>{{ item.time }}</h2>
    </ion-item>
    

    ts:

    getValues(): Array<IShared_Position> {
        return Array.from(this.shared_position.values());
    }
    

    如果您需要这两个值,您可以使用entries-function 将 Map 转换为包含数组的可迭代对象,其中键位于索引 0,值位于索引 1:

    html:

    <ion-item ion-item *ngFor="let item of getEntries()">
        <h2>key: {{ item[0] }} - time: {{item[1].time}}</h2>
    </ion-item>
    

    ts:

    getEntries(): [string, IShared_Position] {
        return Array.from(this.shared_position.entries());
    }
    

    【讨论】:

    • 我还需要 id,不管怎样把 id 放在一边。我收到以下错误:错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngForOf: [object Map Iterator]'。当前值:'ngForOf: [object Map Iterator]'。我想这是因为我在显示 html 后修改了 Map 中的值,但我希望它像往常一样被绑定,从而更新值
    • @ZenoTrevisan 你是对的。 Angular 处理 Iterateables 的方式似乎与 Arrays 不同。我编辑了我的答案,所以它不会抛出这个错误
    • 似乎这将在未来的版本中修复。见github.com/angular/angular/issues/17725
    【解决方案2】:
    <div *ngFor="let item of items | keyvalue">
    {{item.key}}......{{item.value}}
    </div>
    

    【讨论】:

    • 一般来说,答案如果包含对代码或命令的用途以及解决问题的原因的解释会更有帮助。
    • 不用解释了,最正确的方法在这里。
    猜你喜欢
    • 2019-12-16
    • 2018-09-27
    • 2019-01-02
    • 2020-08-09
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多