juanjinario
juanjinario

Reputation: 745

How should the mat-slider be used inside a form configured with formGroup? Angular Material

I have created a form that has inputs of text type and a mat-slider to get a numeric value

// TS
this.consumptionForm = this.formBuilder.group({
      dailyConsumption: ['', Validators.required],
      cost: [20, Validators.required],
    });

// HTML
<form #form="ngForm" [formGroup]="consumptionForm" novalidate>
     <label>Cost</label>
     <mat-slider formControlName="cost" [min]="10" [max]="1000" >
                </mat-slider>


   <div>
           <mat-form-field [floatLabel]="true">
              <mat-label>Daily Consumption</mat-label>
               <input matInput formControlName="dailyConsumption"/>
           </mat-form-field>
        </div>
 </form>

I want the mat-slider to work in conjunction with the rest of the form, and if it is not possible to know which approach is used to use it.

I see that the formControlName is not working

Upvotes: 9

Views: 5099

Answers (2)

Jan Nielsen
Jan Nielsen

Reputation: 11799

With Angular Material v16+, the formControlName for the slider belongs on the slider's matSliderThumb input element:

<mat-slider>
  <input matSliderThumb formControlName="cost" #mySlider>
</mat-slider>

and cost is updated by the slider automatically, as is the mySlider.value template variable.

Upvotes: 1

Eli Trab
Eli Trab

Reputation: 76

It is a little bit old ... Anyway, I used [(value)]="consumptionForm.value.cost" to resolve the same issue, instead of formControlName="cost"

    <mat-slider [min]="10" [max]="1000" [(value)]="consumptionForm.value.cost"></mat-slider>

Upvotes: 1

Related Questions