角度2 * ng如何获取值

时间:2016-06-24 14:40:40

标签: angular ngfor

我有角度为2的pb

<div *ngFor="let elm of elements">
   <h1>  {{elm["0"].value}}</h1> 
</div>

如果它是一个数组,我怎么能访问“elm”的值? 谢谢您的帮助。

4 个答案:

答案 0 :(得分:3)

如果您使用"0"作为密钥,则表示您正在使用object而不是array,因为arrays不能使用字符串文字作为javascript的关键。

因此,您希望使用number来访问它:

<div *ngFor="let elm of elements">
   <h1>{{elm[0].value}}</h1> 
</div>

答案 1 :(得分:2)

如果elements是数组数组:

<div *ngFor="let elm of elements">
    <h1>{{elm["0"]}}</h1> 
</div>

这假设elm["0"]的值是字符串或数字。如果elm["0"]是具有名为value的字符串/数字属性的对象,则使用elm["0"].value

答案 2 :(得分:0)

如果elm是一个数组,你可以像这样访问:

<div *ngFor="let elm of elements">
   <h1>  {{elm[0]}}</h1> 
</div>

但这也有效:

<div *ngFor="let elm of elements">
       <h1>  {{elm["0"]}}</h1> 
</div>

答案 3 :(得分:0)

这是我的代码:

import { Component } from '@angular/core';

const HEROES: Object[] = [
   { id: 11, name: 'Mr. Nice', lastName: 'a' },
   { id: 12, name: 'Narco', lastName: 'b' },
   { id: 13, name: 'Bombasto', lastName: 'a' },
   { id: 14, name: 'Celeritas', lastName: 'b' },
   { id: 15, name: 'Magneta', lastName: 'a' },
   { id: 16, name: 'RubberMan', lastName: 'b' },
   { id: 17, name: 'Dynama', lastName: 'a' },
   { id: 18, name: 'Dr IQ', lastName: 'b' },
   { id: 19, name: 'Magma', lastName: 'a' },
   { id: 20, name: 'Tornado', lastName: 'b' }
 ];

@Component({
   selector: 'my-app',
   template: `
     <h1>{{title}}</h1>
     <h2>My Heroes</h2>
     <div>
        <ul> 
          <li *ngFor="let hero of heroGroupedBy; let i of index">
            <span >{{i}}</span>
            {{hero}}
          </li>
        </ul>
      <button type="submit" (click)=groupByLastName()> group by lastname</button>
     </div>
   `
    })
export class AppComponent {
  heroGroupedBy: Object[];
  arrayOfLastName: Object[];
  title = 'Tour of Heroes';
  heroes = HEROES;

constructor(){
   this.heroGroupedBy = [];
   this.arrayOfLastName = [];
 }


groupByLastName(){
    var groupedBy: any[]
    groupedBy=[];
    this.heroes.map(function(a) {
        if (a.lastName in groupedBy){ groupedBy[a.lastName].push(a); }
        else { groupedBy[a.lastName] = []; 
               groupedBy[a.lastName].push(a); }
    });
    this.heroGroupedBy = groupedBy;
    this.arrayOfLastName = Object.keys(groupedBy);
    console.log(this.heroGroupedBy);
    console.log(this.heroGroupedBy.length);
    console.log(this.arrayOfLastName);
  }
}

控制台的结果:

enter image description here

我不知道为什么长度= 0?