Can I Map through an object in angular?

Viewed 32

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 class="flex items-center px-5 my-3">
        <!-- <img [src]="mock_companies.img" width="20px" /> -->
        <span class="ml-4">
            <h2>{{ taskpilot.companies }}</h2>
        </span>
    </div>
</div>
1 Answers

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