Iterate over object in Angular

前端 未结 17 1360
攒了一身酷
攒了一身酷 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:43

    If someone is wondering how to work with multidimensional object, here is the solution.

    lets assume we have following object in service

    getChallenges() {
        var objects = {};
        objects['0'] = { 
            title: 'Angular2', 
            description : "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
        };
    
        objects['1'] = { 
            title: 'AngularJS', 
            description : "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
        };
    
        objects['2'] = { 
            title: 'Bootstrap',
            description : "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        };
        return objects;
    }
    

    in component add following function

    challenges;
    
    constructor(testService : TestService){
        this.challenges = testService.getChallenges();
    }
    keys() : Array {
        return Object.keys(this.challenges);
    }
    

    finally in view do following

    {{challenges[key].title}}

    {{challenges[key].description}}

提交回复
热议问题