@Input('index') 在 ngfor 循环中保持零

@Input('index') stays zero with ngfor loop

create.component.html

<app-product 
  *ngFor="let product of (products | async); let i = index"  
  [index]="i" 
  [product]="product">
</app-product>

product.component.ts

export class ProductComponent implements OnInit, OnChanges {
  @Input('index') index: number;
  constructor(private store: Store) {
    this.index = 0;
    console.log(this.index)
  }
}

如果我在 create.component.html 中显示索引,为什么我的索引不会随输入字段更新?我可以看到 ngfor 正确地将值 1 赋给输入字段

您在 constructor 中将 index 始终设置为零 (0),并在分配后使用 console.log 打印该值。很明显,它在您的控制台上始终为零。

this.index = 0;
console.log(this.index)

此外,Angular 尚未在构造函数中设置输入。使用 Angular 生命周期方法,例如 OnInit (ngOnInit).

一些提示:

  • 不推荐/不需要输入姓名。 (与 属性 同名)
  • 直接在您的 属性 声明中设置默认值。
  • 一般来说,使用 Angular 生命周期事件而不是构造函数。

这有效(已测试):

<app-product
  *ngFor="let product of products | async; let i = index"
  [index]="i"
  [product]="product"
></app-product>
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-product',
  template: '<div>{{index}} - {{ product | json }}</div>',
})
export class ProductComponent {
  @Input() index = 0;
  @Input() product: unknown;

  constructor(private store: Store) {
    // Expected to be zero. Because input not yet set by Angular.
    console.log(this.index);
  }

  ngOnInit() {
    // Expected to be >= 0. Because you can access the input now. Or use
    console.log(this.index);
    // Here you can also do stuff with this.store.
  }
}

琐事:您还可以使用 OnChanges 来处理每个输入更改。