Search code examples
javascriptangulartypescriptdictionaryngfor

How do I make ngFor for dictionary in Angular?


There is a brandsByLetter class:

brandsByLetter: { [id: string] : AutoServiceBrand[]; } = {};

And I have this construction in angularJS that I need to make in Angular11:

<li *ngFor="let (letter, brands) of brandsByLetter">
    {{letter}}
    {{brands}}
</li>

How do I make "(letter, brands) of" in Angular?


Solution

  • You can use a pipe for that:

    <div *ngFor="let item of brandsByLetter | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    

    add this pipe in your code:

    @Pipe({ name: 'keys',  pure: false })
        export class KeysPipe implements PipeTransform {
            transform(value: any, args: any[] = null): any {
                return Object.keys(value)//.map(key => value[key]);
            }
        }
    

    Here is a working example in Stackblitz:
    https://stackblitz.com/edit/angular-ahsvig?file=src%2Fapp%2Fapp.component.ts