Utilizing angular reactive form to create distance input fields with two boxes labeled as From
and To
.
HTML:
<form [formGroup]="form">
<button (click)="addRow()">Add</button>
<div formArrayName="distance">
<div
*ngFor="let item of form.get('distance').controls; let i = index"
[formGroupName]="i"
style="display: flex"
>
<input type="number" placeholder="From" formControlName="from" />
<div><input type="number" placeholder="To" formControlName="to" /></div>
</div>
</div>
<br /><br />
<button type="submit" [disabled]="!form.valid">Submit</button>
</form>
TypeScript:
ngOnInit() {
this.form = this.fb.group({
distance: this.fb.array([]),
});
this.addRow()
}
addRow() {
const control = this.form.controls.distance as FormArray;
control.push(this.fb.group({
from: ['',Validators.required],
to: ['',Validators.required]
}));
}
The default view displays two input boxes for from
and to
.
An 'add' button is present at the top. Clicking it adds rows with similar input fields arranged as an array.
The requirement is to prevent users from entering a previous row's to
value or any lesser value in the current row's from
input box.
Example scenario - In the first row, if user enters values like 0 and 5 for from
and to
respectively,
"distance": [
{
"from": 0,
"to": 5
}
]
In the next row, when adding values to the from
input box, any value equal to or less than 5 (which has already been entered) is considered invalid.
Therefore, the following configuration is incorrect:
{
"distance": [
{
"from": 0,
"to": 5
},
{
"from": 5,
"to": 10
}
]
}
Values such as "from": 5,
, "from": 4(or)3(or)2(or)1
, are not valid in the second row.
Only values equal to or greater than 6 are acceptable.
This validation needs to be applied for each row by comparing with the previous row's to
value.
Assistance is requested on implementing this type of validation to restrict users from entering a previous row's to
value or a lesser value in the current row's from
field.
Working Example: https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-j58atx
Edit:
Attempted using input change event listener like below,
<input type="number" (input)="onInputChange($event.target.value)" placeholder="From" formControlName="from">
Refer to the link https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-ymfpkj for details, seeking confirmation on correctness of approach.
Please advise on any necessary changes to the procedure if deemed incorrect.