I have many input types created within table by ngFor.There are other variables created with iteration as well
TS
cars=[{id:1232,name:Toyota,bhp:500},
{id:4321,name:Mclaren,bhp:720},
{id:2321,name:Mercedes,bhp:470},
{id:4321,name:Subaru,bhp:342},
{id:5432,name:Mazda,bhp:4321}]
CarForm= new FormGroup({
carNumber: new FormControl(),
});
HTML
<tr *ngFor = "let car of cars" >
<td>
<input type="text" formControlName="carNumber"">
</td>
</tr>
I know that Im able to pass the name value to input like this : CarForm.controls.carNumber.setValue(id)
.
But in this way Im not able to pass specifically row by row. also changed my HTML like below but didnt work
[value]="cars(index).id"
How can I do that?
A good approach as mentioned by @Argee is to use FormArray
. The below approach uses FormBuilder
to build the FormGroup
In your TS File
cars=[
{id:1232,name:'Toyota',bhp:500},
{id:4321,name:'Mclaren',bhp:720},
{id:2321,name:'Mercedes',bhp:470},
{id:4321,name:'Subaru',bhp:342},
{id:5432,name:'Mazda',bhp:4321}]
CarForm = this.fb.group({
cars: this.fb.array(
this.cars.map(({id, name, bhp}) =>
this.fb.group({
id: [id],
name: [name],
bhp: [bhp]
})
)
)
})
get carsArray(): FormArray {
return this.CarForm.get('cars') as FormArray;
}
constructor(private fb: FormBuilder) {
}
In your HTML
Form Value: <br>
<pre>{{CarForm.value | json }}</pre>
<form [formGroup]='CarForm'>
<div formArrayName='cars'>
<div *ngFor="let car of carsArray.controls; let i = index" [formGroupName]='i'><br>
<label [attr.for]="'car-name' + i">Car {{ i + 1 }} Name </label>
<input formControlName='name'><br>
<label [attr.for]="'car-bhp' + i">Car {{ i + 1 }} Bhp </label>
<input formControlName='bhp'>
</div>
</div>
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.