Search code examples
angulartypescriptionic-frameworkrangeionic5

Can't bind ion-range value with ngModel


I'm trying to bind the ion-range value with the default [(ngModel)], but it doesn't seem to be possible. I declared the rangevalue as a number, as mentioned in documentation. I see that someone already managed to do this with Ionic 5 (¹) (²) (³), but I can't find any difference with my method. Although the change() event is triggered each time the range is changed, the same rangeValue value is maintained.

I'm using Ionic 5 with Angular 10.

What I tried to do:

HTML FIRST TRY

<ion-range min="0" max="1" step="0.05" (ionChange)="change()" [(ngModel)]="rangeValue">
    <ion-icon size="small" slot="start" name="sunny"></ion-icon>
    <ion-icon slot="end" name="sunny"></ion-icon>
</ion-range>

HTML SECOND TRY

<ion-range min="0" max="1" step="0.05" (ionChange)="change()" [value]="rangeValue">
    <ion-icon size="small" slot="start" name="sunny"></ion-icon>
    <ion-icon slot="end" name="sunny"></ion-icon>
</ion-range>

TypeScript

private rangeValue: number;

change() {
    console.log('rangeValue: ', this.rangeValue);
}

EDIT

Stackblitz with Ionic 5 and Angular 10, using the same code I'm using, but for my frustration at stackblitz it's working as expected. Perhaps there is something interfering with the correct functioning?


Solution

  • The problem was related to the way the range element was generated, in this case programmatically with a *ngFor. Therefore, ngModel was not linked correctly. To solve this issue I used getElementById() function, even though I didn't find it interesting to get DOM data without using Angular.

    change(programmaticallyGenId) {
        let rangeValue = (<HTMLInputElement>document.getElementById(programmaticallyGenId)).value;
        console.log(rangeValue);
    }