Reputation: 9081
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,
Upvotes: 1
Views: 281
Reputation: 73761
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;
}
}
Upvotes: 1
Reputation: 2943
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>
Upvotes: 1