【问题标题】:@Input('index') stays zero with ngfor loop@Input('index') 在 ngfor 循环中保持为零
【发布时间】:2021-09-18 20:10:46
【问题描述】:

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 赋予输入字段,我的索引为什么不会随输入字段更新

【问题讨论】:

  • 我已将app-product 放在 div 中,并将 ngfor 循环替换为 div,这样我就可以将 i 输出到视图并看到它正确地增加到 1 或 2 或 3

标签: angular typescript 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 来处理每个输入更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2021-10-07
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多