Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructured Assignments in a *ngFor loop

Trying to loop through a JS dictionary in my markup using *ngFor against Object.entries and getting an error message:

Parser Error: Unexpected token [, expected identifier, keyword, or string at column 5 in [let [key, item] of Object.entries(items)]

template:

<button *ngFor="let [key, item] of Object.entries(items)" 
        (click)="itemClicked.emit([key, item.value])">
  {{ item.displayName }}
</button>

typescript:

export interface DropDownItem {
  displayName: string,
  value: any,
  checked: boolean
}

@Component({ /* ... */ })
export class MyComponent {
  @Input() items: { [key: string]: DropdownItem };

  @Output() itemClicked = new EventEmitter<[string, any]>();

  Object = Object;

  constructor() { }
}
like image 290
ZackDeRose Avatar asked Dec 24 '22 06:12

ZackDeRose


1 Answers

Ended up with this in my markup; ts unchanged.

<button *ngFor="let key of Object.keys(items)"
        (click)="itemClicked.emit([key, items[key].value])">
  {{ items[key].displayName }}
</button>

Still wish I could destructure the Object.entries() in my markup, but looks like destructing is not currently an option for *ngFor.

I found this feature request from a few years ago asking for destructuring in *ngFor syntax, and they said they would pass on this feature.... but I'm really hoping they consider re-opening it.

like image 87
ZackDeRose Avatar answered Feb 06 '23 08:02

ZackDeRose