st_clair_clarke
st_clair_clarke

Reputation: 5715

Accessing a map's key and value with @ngFor in Dart

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:

.dart

 Map people = [
    { name: 'Anderson', age: 35, city: 'Sao Paulo' },
    { name: 'John', age: 12, city: 'Miami' },
    { name: 'Peter', age: 22, city: 'New York' }
  ];

.html

<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

EDIT1 - clarification

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?

Upvotes: 1

Views: 6531

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658037

Instead of

<td>{{<!--place the value of the maps key here-->}}</d>

use

<td>{{p.keys}}</td>

Recreating your example Dart loop is more laborious because p.keys returns a new iterable for each call. That produces the error message in development mode

EXCEPTION: Expression 'p.keys in AppElement@3:12' has changed after it was checked.

To work around this I created a pipe to remember the previous keys-iterable

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;
  }
}

Upvotes: 1

SnareChops
SnareChops

Reputation: 13347

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>

Upvotes: 0

Related Questions