【问题标题】:*ngFor fails in angular 2*ngFor 在角度 2 中失败
【发布时间】:2017-03-04 09:46:36
【问题描述】:

我正在尝试使用 *ngFor 来访问对象数组。但它会引发控制台错误。我已经像这样定义了数组。

     employees=[ 
        {name:'a',age:'25'},
        {name:'b',age:'35'}
        ];

在 html 模板文件中,我使用 *ngFor 这样的语句

        <ul>
         <li *ngFor="let employee of employees ; let i = index;">
           {{name}}
        </li>
       </ul>

浏览器抛出如下控制台错误(plukr 为@http://plnkr.co/edit/0cBHaDM1mHvMf38NtQ7X?p=preview

错误:未捕获(在承诺中):错误:错误:0:0 导致:Array[2] 不是构造函数 TypeError: Array[2] 不是构造函数 在新的 AppComponent (http://run.plnkr.co/0tyHWvPl7PnWfPkm/app/app.component.ts!transpiled:15:26) 在新的 Wrapper_AppComponent

我对 Angular 2 有点陌生,任何帮助都将不胜感激。

【问题讨论】:

    标签: angular typescript angular2-ngfor


    【解决方案1】:

    错误

    1. 您使用了 index.html 中的标记。
    2. employees= new Array[2]; 不是实例化数组的方法。
    3. names = new Array('qw','er'); 无效。
    4. 没有使用构造函数来赋值。(不好的做法)

    你的代码应该是

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `<h1>Hellotest {{name}}</h1>
      <ul>
             <li *ngFor="let name of names ; let j = index;">
               {{name}}
               </li>
           </ul>
            <ul>
             <li *ngFor="let employee of employees ; let i = index;">
               {{employee.name}}
            </li>
           </ul>
           `
    })
    export class AppComponent { 
      name = 'Angular';
      employees= new Array();
      names = new Array();
      constructor(){
      this.employees=[ 
        {name:'a',age:'25'},
        {name:'b',age:'35'}
        ];
    
      this.names=['qw','er'];
      console.log(this.employees);
      console.log(this.names);
      }
    }
    

    Updated plunker

    如果你不想使用构造函数,那么你应该使用如下的变量声明

      name = 'Angular';
      employees:any[]= [ 
        {name:'a',age:'25'},
        {name:'b',age:'35'}
        ];
      names:Array<string> = ['qw','er'];
    

    No Constructor plunker

    【讨论】:

    • 谢谢..帮助
    【解决方案2】:

    请将您的布局更改为:

    <ul>
       <li *ngFor="let employee of employees ; let i = index;">
          {{employee.name}}
       </li>
    </ul>
    

    employee 变量将是数组的每个元素,然后您需要访问此对象的 name 属性

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2017-06-01
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多