Iterate over object in Angular

前端 未结 17 1562
攒了一身酷
攒了一身酷 2020-11-22 12:19

I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.

I have an interface in TypeScript looking like this:

17条回答
  •  日久生厌
    2020-11-22 12:58

    It appears they do not want to support the syntax from ng1.

    According to Miško Hevery (reference):

    Maps have no orders in keys and hence they iteration is unpredictable. This was supported in ng1, but we think it was a mistake and will not be supported in NG2

    The plan is to have a mapToIterable pipe

    So in order to iterate over your object you will need to use a "pipe". Currently there is no pipe implemented that does that.

    As a workaround, here is a small example that iterates over the keys:

    Component:

    import {Component} from 'angular2/core';
    
    @Component({
      selector: 'component',
      templateUrl: `
           
    • {{key}}:{{myDict[key]}}
    ` }) export class Home { myDict : Dictionary; constructor() { this.myDict = {'key1':'value1','key2':'value2'}; } keys() : Array { return Object.keys(this.myDict); } } interface Dictionary { [ index: string ]: string }

提交回复
热议问题