1

I need to bind an array of number in two ways with a set of input number:

Ligne.Component.ts

export class LigneComponent implements OnInit {

  @Input() cells: Array<number>;

  constructor(private lgservice: LigneserviceService ) {
    this.lgservice.init(4032,10);
    this.cells = this.lgservice.cells;
    }

  ngOnInit() {
  }
  onSearchChange() {

      for (let cell of this.cells) {
      {
        console.log(cell);
      }
  }
}

Ligne.Component.html

<div *ngFor="let cell of cells">
  <input value="{{cell}}" type="number" [min]="0" [max] ="9" maxlength="1" class="row" (input)="onSearchChange()" >
</div>

It seems that the binding works in a single ways ie : I get the default values ( equal 0 ). But when I Change the value of the cells I get always 0 as value of all cells !!

So I need to know how can I fix this problem?

Thanks,

2 Answers 2

1

You are using incorrect binding for value. You should use ngModel here. Also your cell should be an object with some field holding a number inside it. Then change your template slightly:

<div *ngFor="let cell of cells">
  <input [(ngModel)]="cell.field" type="number" [min]="0" [max] ="9" maxlength="1" class="row" (input)="onSearchChange()" >
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

I get this error Uncaught Error: Cannot assign to a reference or variable!
Then you probably need to make your cell an object with the field inside it. And use this field in ngModel as cell.field. I'll edit my answer.
1

You can use [(ngModel)] for two-way data binding but not with the template reference variable. Instead, you should refer to the cells item with the array index. In order for the binding to work correctly, you also need to track the items by the index with trackBy, as shown in this stackblitz:

<div *ngFor="let cell of cells; let i=index; trackBy: trackByIndex;">
  <input [(ngModel)]="cells[i]" type="number" [min]="0" [max]="9" maxlength="1" class="row" (input)="onSearchChange()">
</div>

with the code:

export class LigneComponent implements OnInit {

  @Input() cells: Array<number>;

  ...

  trackByIndex(index: number, cell: any): any {
    return index;
  }
}

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.