Could somebody help me with the following code and give me a reason why it does not work. I am creating a series of inputs from a string array and I want to bind each input value to its corresponding slot in the string array. Seems to be pretty standard, but I do not seem to grasp the issue.
I have tried the following two cases, but the Colors array (=string[]) remains empty!
<tr *ngFor="let color of Colors; let i = index;">
<td>
<mat-form-field>
<input required matInput placeholder="Color ({{ i + 1}})" [name]="'color_' + i" [(ngModel)]="color">
</mat-form-field>
</td>
</tr>
<tr *ngFor="let color of Colors; let i = index;">
<td>
<mat-form-field>
<input required matInput placeholder="Color ({{ i + 1}})" [name]="'color_' + i" [(ngModel)]="Colors[i]">
</mat-form-field>
</td>
</tr>
Strings are immutable in JavaScript, meaning we cant bind ngModel to them. You could quite easily convert your array into an array on objects with the key color and the value of your strings. This would fix your binding issue. Here is some code. I also hacked together a stackbitz to show you.
However, I would recommend Joey gough's answer though. That code feels more correct and "the angular way" of solving this. Good luck!
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
Colors = [{color: 'stringColor1'}, {color: 'stringColor2'}]
}
<tr *ngFor="let item of Colors; let i = index;">
{{i}}
<td>
<input required placeholder="Color ({{ i + 1}})" [name]="'color_' + i" [(ngModel)]="item.color">
</td>
</tr>
{{Colors | json}}