Home > Blockchain >  Can I Map through an object in angular?
Can I Map through an object in angular?

Time:09-07

I have been able to get data from a swagger endpoint, it displays on the console but throws an error whenever I try to loop through it and display its properties on the template view.

I get an error as shown below in the red area: Object Object error

in the component.ts the data is passed through a service and console.logged:

export class CompanyDialogComponent  implements OnInit{

  taskpilot!: IGetTaskPilot[];

  constructor( private domainService: DomainService) {}
    ngOnInit(): void {
    
        this.domainService.getTaskPilot().subscribe({
            next:(response) => {
                this.taskpilot = response;
                console.log(response);
                return response;
            },
        });
    }
}

on the template:

<div *ngFor="let taskpilot of taskpilot">
    <div >
        <!-- <img [src]="mock_companies.img" width="20px" /> -->
        <span >
            <h2>{{ taskpilot.companies }}</h2>
        </span>
    </div>
</div>

CodePudding user response:

You cannot map trough object properties directly in angular template.

Unfortunately, ngFor only accepts 'of' and not 'in'. But fear not, you can do this:

add a simple method to get the keys of an object as array:

keys<T extends any>(obj:T):(keyof T)[]{
  return Object.keys(obj) as (keyof T)[];
}

then you can use the for loop with it:

<div *ngFor="let prop of keys(taskpilot)">
    {{prop}}: {{taskpilot[prop]}}
</div>

EDIT:

You could also simply use the existing keyvalue pipe.

<div *ngFor="let prop of taskpilot | keyvalue">
    {{prop.key}}: {{prop.value}}
</div>
  • Related