Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 2 Key Value Pipe
import { Pipe, PipeTransform } from '@angular/core';
/*
* Enables the key/value pair of an item to be
* visible within an ngFor
* Usage:
* value of iteratable | keyValue
* Example:
* <ul>
* <li *ngFor='key of demo | keyValue'>
* Key: {{key.key}}, value: {{key.value}}
* </li>
* </ul>
*/
@Pipe({ name: 'keyValue' })
export class KeyValuePipe implements PipeTransform {
transform(value, args: string[]): any {
let keys = [];
for (let key in value) {
keys.push({ key: key, value: value[key]});
}
return keys;
}
}
@Snap252

This comment has been minimized.

Copy link

Snap252 commented Jul 30, 2018

what about type safety ?

transform<T, U extends { [id: string]: T } | { [id: number]: T }>(value: U, args?: any): { key: keyof U, value: U[keyof U] }[] {
	const keys: {key: keyof U, value: U[keyof U]}[] = [];
	  for (const key in value) {
		keys.push({key: key, value: value[key]});
	  }
	return keys;
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.