I don't know if its possible but I have been searching and did not see any information relating to accessing the key of the map using *ngFor.
Given:
Map people = [
{ name: 'Anderson', age: 35, city: 'Sao Paulo' },
{ name: 'John', age: 12, city: 'Miami' },
{ name: 'Peter', age: 22, city: 'New York' }
];
<table class="ui celled table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tr *ngFor="#p of people">
<td>{{<!--place the value of the maps key here-->}}</d>
<td>{{ p.name }}</td>
<td>{{ p.age }}</td>
<td>{{ p.city }}</td>
</tr>
</table>
Is it possible to place the string value of the key at the position indicated?
Thanks
In dart the for loop can be used as shown below to access the key and value of the map
map.forEach((k, v)
{
print('key|$k, value|$v');
});
Does the *ngFor offer any such mechanism?
答案 0 :(得分:0)
To get the index of the current item in the array you can use $index
<tr *ngFor="#p of people; #idx = $index">
<td>{{ idx }}</d>
<td>{{ p.name }}</td>
<td>{{ p.age }}</td>
<td>{{ p.city }}</td>
</tr>
答案 1 :(得分:0)
而不是
<td>{{<!--place the value of the maps key here-->}}</d>
使用
<td>{{p.keys}}</td>
重新创建示例Dart循环更加费力,因为p.keys
为每个调用返回一个新的可迭代。这会在开发模式中生成错误消息
EXCEPTION:AppElement @ 3:12中的表达式'p.keys'在检查后发生了变化。
为了解决这个问题,我创建了一个管道来记住以前的密钥可迭代
import 'package:angular2/core.dart'
show Component, View, Pipe, PipeTransform;
import 'package:collection/collection.dart';
@Component(selector: 'app-element', pipes: const [MapKeysPipe],
template: '''
<h1>app-element</h1>
<table>
<tr *ngFor="let p of people">
<td><span *ngFor="let k of p | mapKeys">{{'key|' + k + ', value|' + p[k].toString()}}</span></td>
<td>{{ p['name'] }}</td>
<td>{{ p['age'] }}</td>
<td>{{ p['city'] }}</td>
</tr>
</table>
''')
class AppElement {
List people = [
{'name': 'Anderson', 'age': 35, 'city': 'Sao Paulo'},
{'name': 'John', 'age': 12, 'city': 'Miami'},
{'name': 'Peter', 'age': 22, 'city': 'New York'}
];
}
@Pipe(name: 'mapKeys')
class MapKeysPipe extends PipeTransform {
Iterable prevKeys;
dynamic transform(Map value, List args) {
if (prevKeys != null &&
value != null &&
const UnorderedIterableEquality().equals(prevKeys, value.keys)) {
return prevKeys;
}
prevKeys = value.keys;
return prevKeys;
}
}