I am building an app Using Angular 5 and I am trying to build a dynamic form. This form, which is like a bet slip or shopping cart, is a array of objects which comes from a service as an observable. I am having difficulty figuring out how to add an input field and bind it to a property in each bet object.
The observable betSlipItems array looks like this:
[
{
"Id": 1,
"betslipTeamName": "La Rochelle",
"stake": null
},
{
"Id": 2,
"betslipTeamName": "North Queensland Cowboys",
"stake": null
}
]
And what I want to do is create an input field and bind it to the 'stake' property of each bet object.
This is my code for bet-slip.component.ts so far:
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';
import { Bets } from '../../../shared/models';
import { BetService } from '../../../shared/services/bet.service';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
@Component({
selector: 'bet-slip',
templateUrl: './bet-slip.component.html',
styleUrls: ['./bet-slip.component.scss']
})
export class BetSlipComponent implements OnInit {
public betSlipItems$: Observable<Bets[]> = of([]);
public betSlipItems: Bets[] = [];
public betsForm: FormGroup;
constructor( private betService: BetService, private _fb: FormBuilder) {
this.betSlipItems$ = this.betService.getBets();
}
ngOnInit() {
this.betsForm = new FormGroup({
stake: new FormControl()
});
this.betSlipItems$.subscribe((betSlipItems) => {
this.betSlipItems = betSlipItems;
});
}
}
and my component bet-slip.component.html looks like this:
<form [formGroup]="betsForm">
<div *ngFor="let bet of betSlipItems; let i=index">
{{bet.betslipTeamName }}
<input type="text" formControlName="stake">
</div>
</form>
I know this is incorrect. How can I fix this?