Reputation: 63
I have a data form database like this, `
{
noOfChildren : 2,
childAge:[4,5]
}
`
I am trying to code to edit page these thing.
<div class="form-group">
<label for="flightChild" class="label">No of Children in Flight (2YRS - 17YRS)
</label>
<input type="number" min="0" max="9" nbInput fullWidth id="flightChild" placeholder="No of Children in Flight"
formControlName="flightChild"
(keyup)="onNoOfChild($event)"/>
</div>
<div *ngIf="noOfChild > 0" class="row" >
<div id="flightChildAge" class="col-md-4">
<div class="form-group">
<label for="flightChildAge" class="label">Children's age
</label>
<input type="number" min="3" max="17" nbInput fullWidth id="flightChildAge" placeholder="Children's age"
formControlName="flightChildAge" />
</div>
</div>
</div>
**I have tried this code. BUT I NEED TO MODIFY
If noOFChild =1, then no of input tag for child's age = 1.
If noOFChild =2, then no of input tag for child's age = 2.
If noOFChild =1, then no of input tag for child's age = 3.
If noOFChild =1, then no of input tag for child's age = 4. and so on..**
How to do this in angular?
Upvotes: 0
Views: 534
Reputation: 146
For step by step instructions check https://angular.io/guide/reactive-forms#creating-dynamic-forms
Briefly:
youeForm = this.fb.group({
noOfChildren : [1, Validators.required],
flightChildAge: this.fb.array([])
});
for (let index = 0; index < this.model.noOfChildren; index++) {
this.flightChildAges.push(this.fb.control(0));
}
this is the getter for child ages control
get flightChildAges() {
return this.youeForm.get('flightChildAge') as FormArray;
}
Your template:
<div *ngFor="let child of flightChildAges.controls; let i=index">
<label for="child-{{ i }}">Children's age:</label>
<input id="child-{{ i }}" type="text" [formControlName]="i">
</div>
You assign the index to the i variable and pass it to each control to bind it to the formControlName input.
Upvotes: 1