Created
April 1, 2020 03:04
-
-
Save Qarun-Qadir-Bissoondial/28ac17d0fd32fc40b46a951cf56eae9d to your computer and use it in GitHub Desktop.
Pipes Demo - Key-Value Pipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { KeyValue } from '@angular/common'; | |
interface Item { | |
name: string; | |
price: number; | |
expDate: number; | |
} | |
@Component({ | |
selector: 'app-key-value-pipe', | |
template: ` | |
<h3>Default Key-Value pipe</h3> | |
<p *ngFor = "let item of person | keyvalue"> | |
{{item.key}} - {{item.value}} | |
</p> | |
<h3>Custom Sort functions:</h3> | |
<h4>Sort by decreasing length of string values</h4> | |
<p *ngFor = "let item of person | keyvalue:customCompareFn"> | |
{{item.key}} - {{item.value}} | |
</p> | |
<h4>Sort by increasing expiry dates</h4> | |
<p *ngFor = 'let item of inventory | keyvalue:increasingExpDate'> | |
{{item.value.name}} expires at {{item.value.expDate | date}} | |
</p> | |
`, | |
styleUrls: [] | |
}) | |
export class KeyValuePipeComponent { | |
person: object = { | |
name: 'Qarun', | |
age: '25', | |
food: 'Cheesecake' | |
}; | |
milliseconds: number = 1000 * 60 * 60 * 24; | |
inventory: Item[] = [ | |
{ | |
name: 'Cabbage', | |
price: 5, | |
expDate: Date.now() + (this.milliseconds * 14) | |
}, | |
{ | |
name: 'Lettuce', | |
price: 10, | |
expDate: Date.now() + (this.milliseconds * 21) | |
}, | |
{ | |
name: 'Tomatoes', | |
price: 15, | |
expDate: Date.now() + (this.milliseconds * 17) | |
}, | |
] | |
constructor() { } | |
customCompareFn(a: KeyValue<string, string>, b: KeyValue<string, string>) { | |
if (a.value.length > b.value.length) return -1; | |
if (a.value.length === b.value.length) return 0; | |
if (a.value.length < b.value.length) return 1; | |
} | |
increasingExpDate(a: KeyValue<number, Item>, b: KeyValue<number, Item>) { | |
if (a.value.expDate < b.value.expDate) return -1; | |
if (a.value.expDate === b.value.expDate) return 0; | |
if (a.value.expDate > b.value.expDate) return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment