1

I've a custom number picker component component with @Input and @Output parameters:

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;
    }
  }

}

It's working well in a simple template.

The problem apperars when its binded to an array inside a *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;
  }
}

You could see than the first two pickers are not working well, but the third (same as second) it's OK.

How can I bind the picker inside the ngFor?

I've a plnkr with the all the code: https://plnkr.co/edit/aNh23TSnkhdfLnm8Ypq1?p=preview

Thank's in advance.

1 Answer 1

1

Your should not permanently change the input of your app-number-picker component. In onAgeChanged store the values in a variable other than ages.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.