可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm pulling in JSON data from an external data source and part of the payload is an array that needs to be displayed as a series of key/value pairs.
I realize one way would be to transform the array into an interface/object via Typescript but in my case the data needs to be transformed declaratively in the Angular template's html markup.
So, given some data in the form of: heroes = ['Hurricane', 12, 'Wolf', 42, 'Zephyr', 28]
Displaying the data via *ngFor:
<div *ngFor="let hero of heroes"> {{hero}} </div>
would render:
Hurricane
12
Wolf
42
Zephyr
28
However, what I need to display is:
Hurricane - 12
Wolf - 42
Zephyr - 28
Is there a way to do this declaratively inside the Angular 2 template file?
See Plunkr here
回答1:
You could transform the array you received using Array Extras into objects that better fit your view.
['Hurricane', 12, 'Wolf', 42, 'Zephyr', 28] .map(function(curr, index, arr) { if(typeof curr === 'number') return {name: arr[index-1], id: curr } }) .filter(function(val) { return val })
https://blogs.msdn.microsoft.com/ie/2010/12/13/ecmascript-5-part-2-array-extras/
回答2:
you can change heroes = [{name:'Hurricane', age:12}, {name:'Wolf', age:42}, {name:'Zephyr', age:28}]
Display the data <div *ngFor="let hero of heroes"> {{hero.name}} - {{hero.age}} </div>
回答3:
I created a function inside the component using cboston's code:
mapArray(args){ var results = args.map(function (current, index, arr) { if(typeof current == 'number'){ return { name: arr[index - 1], age: current } } }).filter(function(val) { return val; }); return results; }
Then, the Angular 2 client side markup looks like this:
<div *ngFor="let hero of mapArray(heroes)"> {{hero.name}} : {{hero.age}} </div>
Plunk available here: http://plnkr.co/edit/YnIL5drfWzIL5gMc1Efd?p=info