I'm working with Reactive Forms way. I want to bind values into an array of strings, for example:
The list of fruits will be populated in the input radio.
//<pre>{{ form.value | json }}</pre>
{
"favorite_fruits": [
"Banana",
"Apple",
]
}
<form [formGroup]="form" >
<pre>{{ form.value | json }}</pre>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
<button type="button" (click)="getFavoriteFruits().push(createFavoriteFruits())" class="btn btn-primary btn-sm">add FavoriteFruits</button>
</div>
<div formArrayName="favorite_fruits" *ngFor="let h of getFavoriteFruits()!.controls; let indexFavoriteFruits = index;">
<div class="form-group col-md-12">
<label id="">Favorite Fruits</label>
<div *ngIf="(fruits$ | async) as fruits">
<div *ngFor="let fruit of fruits; let indexFruit = index;">
<input type="radio" [formControlName]="indexFavoriteFruits" [value]="fruit.name">{{ fruit.name }}
</div>
</div>
</div>
</div>
</form>
ngOnInit(): void {
this.getFruits();
this.form = this.formBuilder.group({
"favorite_fruits": this.formBuilder.array([
this.createFavoriteFruits()
]),
});
}
createFavoriteFruits() {
return this.formBuilder.control('', []);
}
getFavoriteFruits(): FormArray {
return this.form.get('favorite_fruits') as FormArray;
}
getFruits() {
this.fruits$ = of ([{
"id": 1,
"name": "Banana"
}, {
"id": 2,
"name": "Apple"
}, {
"id": 3,
"name": "Pear"
}])
.pipe(
delay(2000)
)
}
I was trying to using [formControlName]="indexFavoriteFruits" (inside brackets) and the error below was given:
error TS2322: Type 'number' is not assignable to type 'string'.
<input type="radio" [formControlName]="indexFavoriteFruits" [value]="fruit.name">{{ fruit.name }}
I also tried to using formControlName="indexFavoriteFruits", but I got another error:
core.js:6456 ERROR Error: Cannot find control with path: 'favorite_fruits -> indexFavoriteFruits'
You might want to try using formControlName="favorite_fruits"
indexFavoriteFruits is the index you are getting in the *ngFor, thats why it is interpreted as number. The correct formcontrolname is favorite_fruits
It seems that you're using Angular version < v9, which accept only a string as a value for formControlName. Which is changed since Angular v9 to accept string|number|null.
So, you need to cast the indexFavoriteFruits to a string or any because the formControlName accepts strings only.
You can cast it to any using $any method, like the following:
<input type="radio" [formControlName]="$any(indexFavoriteFruits)" [value]="fruit.name">