Issue
I would like to synchronize the min
and max
values of a ranged mat-slider with corresponding input fields. When I set numbers in the input fields the slider gets correct updated but when I use the slider to change the value of the input fields the slider behaves strange.
HTML:
<form [formGroup]="sampleForm">
<input
type="number"
[min]="0"
[max]="sampleForm.value.max"
[formControlName]="'min'"
>
<input
type="number"
[min]="sampleForm.value.min"
[max]="100"
[formControlName]="'max'"
>
<mat-slider min="0" max="100">
<input [formControlName]="'min'" matSliderStartThumb [value]="sampleForm.value.min">
<input [formControlName]="'max'" matSliderEndThumb [value]="sampleForm.value.max">
</mat-slider>
</form>
TS:
export class SliderRangeExample implements OnInit {
sampleForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.sampleForm = this.fb.group({
min: 0,
max: 100,
});
this.sampleForm.controls.min.valueChanges.subscribe((value) => {
this.sampleForm.controls.min.setValue(value, { emitEvent: false });
});
this.sampleForm.controls.max.valueChanges.subscribe((value) => {
this.sampleForm.controls.max.setValue(value, { emitEvent: false });
});
}
}
I can solve this by adding two more formControls to the sampleForm like inputMin and inputMax (using them for the input fields) and set the values in the subscription but I thought there is a better solution only using min and max. Highly appreciate any ideas on this!
Solution
You can not use two "inputs" with the same formControl
, but...
You can use [ngModel] and (ngModelChange) to change and show the value of a FormControl
Imagine you have a formControl control
, you can write
<input [formControl]="control">
<input [ngModel]="control.value"
(ngModelChange)="control.setValue($event)">
So, in your case, you can use some like
<form *ngIf="sampleForm" [formGroup]="sampleForm">
<input type="number" [min]="0" [max]="sampleForm.value.max"
[ngModel]="sampleForm.get('min')?.value"
(ngModelChange)="sampleForm.get('min')?.setValue($event)"
[ngModelOptions]="{standalone:true}"
/>
<input type="number" [min]="sampleForm.value.min" [max]="100"
[ngModel]="sampleForm.get('max')?.value"
(ngModelChange)="sampleForm.get('max')?.setValue($event)"
[ngModelOptions]="{standalone:true}"
/>
<mat-slider min="0" max="100">
<input formControlName="min" matSliderStartThumb/>
<input formControlName="'max'" matSliderEndThumb/>
</mat-slider>
</form>
See that you need use [ngModelOptions]="{standalone:true}"
because you're using a [ngModel]
inside a FomGroup
See stackblitz
- NOTE: I choose the inputs type number to transform the
FormControlName
yngModel
, but you can also choose the inputs in sliders - NOTE2: see that when you use a formControl NOT use
[value]
- NOTE3: you can use
formControlName="min"
instead of[formControlName]="'min'"
, it's unnecessary "binding" if it's a constant.
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.