Angular 2+ Component绑定到ngFor内的数组

时间:2018-06-18 14:51:38

标签: angular angular2-template ngfor

我有一个带@Input和@Output参数的自定义数字选择器组件:

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

@Component({
  selector: 'app-number-picker',
  templateUrl: './number-picker.component.html',
  styleUrls: ['./number-picker.component.css']
})
export class NumberPickerComponent implements OnInit {
  @Input() value: number = 0;
  @Input() min: number = 0;
  @Input() max: number = 9999;
  @Output() output = new EventEmitter<number>();

  enabled1: boolean = true;
  enabled2: boolean = true;

  constructor() { }

  ngOnInit() {
  }

  add() {
    if (this.value < this.max) {
      this.value++;
      this.output.emit(this.value);
    }
    this.enabled1 = true;
    if (this.value == this.max) {
      this.enabled2 = false;
    }
    else {
      this.enabled2 = true;
    }
  }

  remove() {
    if (this.value > this.min) {
      this.value--;
      this.output.emit(this.value);
    }
    this.enabled2 = true;
    if (this.value == this.min) {
      this.enabled1 = false;
    }
    else {
      this.enabled1 = true;
    }
  }

}

它在一个简单的模板中运行良好。

当问题绑定到* ngFor:

内的数组时,问题会出现
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Picker 1 & 2 seems connected in a strange way</h2>
      <div *ngFor="let age of ages;let i = index">
        <app-number-picker [value]="age" (output)="onAgeChanged($event, i)"></app-number-picker>
      </div>

      <h2>Picker 2 works well if it's outside ngFor but still binded to the array</h2>
      <app-number-picker [value]="ages[1]" (output)="onAgeChanged($event, 1)"></app-number-picker>
    </div>
  `,
})
export class App {
  ages: number[] = [2,2];
  constructor() {
    this.name = `Plunker! v${VERSION.full}`;
  }

  onAgeChanged(value, index) {
    console.log('index', index);
    this.ages[index] = value;
  }
}

你可以看到前两个选择器不能正常工作,但第三个(与第二个相同)没关系。

如何在ngFor?

中绑定选择器

我有一个包含所有代码的plnkr:https://plnkr.co/edit/aNh23TSnkhdfLnm8Ypq1?p=preview

提前感谢。

1 个答案:

答案 0 :(得分:1)

您不应永久更改app-number-picker组件的输入。在onAgeChanged中,将值存储在ages以外的变量中。

Forked Plunker:https://next.plnkr.co/edit/dGE7utsQ9wRL7IcS