【问题标题】:Angular 2+ Component binded to array inside a ngForAngular 2+ 组件绑定到 ngFor 内的数组
【发布时间】:2018-11-27 11:04:08
【问题描述】:

我有一个带有@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

提前致谢。

【问题讨论】:

    标签: angular angular2-template ngfor


    【解决方案1】:

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

    分叉的 Plunker:https://next.plnkr.co/edit/dGE7utsQ9wRL7IcS

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 2017-02-28
      • 2017-12-23
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多