*ngFor 在 angular 2 中失败
*ngFor fails in angular 2
我正在尝试使用 *ngFor 访问对象数组。但它正在抛出 console errors.I 已经定义了这样的数组。
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 引起的:数组 [2] 不是构造函数
TypeError: Array[2] 不是构造函数
在新的 AppComponent (http://run.plnkr.co/0tyHWvPl7PnWfPkm/app/app.component.ts!transpiled:15:26)
在新 Wrapper_AppComponent
我对 Angular 2 有点陌生,非常感谢任何帮助。
请将布局更改为:
<ul>
<li *ngFor="let employee of employees ; let i = index;">
{{employee.name}}
</li>
</ul>
employee 变量将是您数组的每个元素,然后您需要访问此对象的名称属性
错误
- 您使用了 index.html 中的标记。
employees= new Array[2];
不是实例化数组的方法。
names = new Array('qw','er');
无效。
- 没有使用构造函数来赋值。(不好的做法)
你的代码应该是
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);
}
}
如果您不想使用构造函数,那么您应该使用如下的变量声明
name = 'Angular';
employees:any[]= [
{name:'a',age:'25'},
{name:'b',age:'35'}
];
names:Array<string> = ['qw','er'];
我正在尝试使用 *ngFor 访问对象数组。但它正在抛出 console errors.I 已经定义了这样的数组。
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 引起的:数组 [2] 不是构造函数 TypeError: Array[2] 不是构造函数 在新的 AppComponent (http://run.plnkr.co/0tyHWvPl7PnWfPkm/app/app.component.ts!transpiled:15:26) 在新 Wrapper_AppComponent
我对 Angular 2 有点陌生,非常感谢任何帮助。
请将布局更改为:
<ul>
<li *ngFor="let employee of employees ; let i = index;">
{{employee.name}}
</li>
</ul>
employee 变量将是您数组的每个元素,然后您需要访问此对象的名称属性
错误
- 您使用了 index.html 中的标记。
employees= new Array[2];
不是实例化数组的方法。names = new Array('qw','er');
无效。- 没有使用构造函数来赋值。(不好的做法)
你的代码应该是
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);
}
}
如果您不想使用构造函数,那么您应该使用如下的变量声明
name = 'Angular';
employees:any[]= [
{name:'a',age:'25'},
{name:'b',age:'35'}
];
names:Array<string> = ['qw','er'];