角度-模板中的“ let”如何工作?

时间:2019-11-26 13:14:42

标签: angular

*ngFor="let item of shoppingList;"

以上模板代码如何工作?

更具体地说,let在模板中如何工作?

这是我组件中的代码:

@Input()
public set shoppinglist(shoppingList: ShoppingItem[]) {
  this._shoppinglist = shoppingList;
}
public get shoppinglist(): ShoppingItem[] {
  return this._shoppinglist;
}

private _shoppinglist: ShoppingItem[] = [];

*ngFor="let item of shoppingList;"*ngFor="let item of _shoppingList;"为何都起作用?

1 个答案:

答案 0 :(得分:0)

*ngFor="let item of shoppingList

与在typescript中迭代数组基本相同,它从array创建一个新项:

let shoppingList: ShoppingList[] = [
  {
    id: 1,
    name: "TEST 1"
  },
  {
    id: 2,
    name: "TEST 2"
  },
  {
    id: 3,
    name: "TEST 3"
  }
];

for (let item of shoppingList) {
  console.log(item);
}

//  OUTPUT
//  { id: 1, name: 'TEST 1' }
//  { id: 2, name: 'TEST 2' }
//  { id: 3, name: 'TEST 3' }

_shoppingList和shoppingList在您的情况下工作相同,因为您得到的是相同的东西(_shoppingList),区别仅在于通过getter获得的shoppingList。