【问题标题】:Differing *ngFor behaviour between Angular 8 and Angular 10Angular 8 和 Angular 10 之间的不同 *ngFor 行为
【发布时间】:2021-02-24 13:20:28
【问题描述】:

我最近将一个项目从 Angular 8 更新到 Angular 10,但遇到了一些问题。我正在遍历两个单独的列表并显示数据

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

@Component({
  selector: 'my-app',
  template: `
  <div *ngFor="let column of columns; let i of index">
    Field: {{column['field']}} 
    <br>
    Name: {{column['name']}} 
    <br>
    Index: {{i}}
  </div>`
})
export class AppComponent  {
  @Input() name: string;
  columns: object[] = [
    {field: 'FIELD_A', name:'NAME_A'},
    {field: 'FIELD_B', name:'NAME_B'}
    ];
  index: number[] = [0,1];
}

在 Angular 8 中,我的输出看起来像

Field: FIELD_A
Name: NAME_A
Index: [object Object]
Field: FIELD_B
Name: NAME_B
Index: [object Object]

在角度 10 中,我的输出看起来像

Field:
Name:
Index: 0
Field:
Name:
Index: 1

我的问题是:

  1. 为什么版本之间的这种行为不同?这是一个错误还是故意的?
  2. 为什么 Angular 8 将索引显示为对象?

请注意,将 let i of index 替换为 let i = index 会为两者提供正确一致的输出

Field: FIELD_A
Name: NAME_A
Index: 0
Field: FIELD_B
Name: NAME_B
Index: 1

【问题讨论】:

    标签: angular typescript angular8


    【解决方案1】:

    关于 Index 你使用了错误的语法,这里是正确的:

    <div *ngFor="let column of columns; let index = index">
    

    关于版本迁移: 默认情况下,Angular 10 对模板类型检查使用严格模式。 由于它无法用您的语法检查它,我会假设它不会显示它。 您可以通过直接调用属性来更改它:

    Field: {{column.field}} 
        <br>
        Name: {{column.name}} 
    

    【讨论】:

    • 谢谢你的解释!我偶然发现了正确的解决方案(上图),但只是不确定为什么我最初的尝试不起作用
    【解决方案2】:

    您不应使用您的 NgForOf-syntax 变体,因为它与 API 参考 (https://angular.io/api/common/NgForOf) 不对应。 你应该使用类似的东西:

    <div *ngFor="let column of columns; index as i">
        Field: {{column['field']}} 
        <br>
        Name: {{column['name']}} 
        <br>
        Index: {{i}}
      </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2020-02-01
      • 2021-09-26
      相关资源
      最近更新 更多