Yann92
Yann92

Reputation: 383

ion-range disabled when I want to select 0

I have an ion-range where the user can select a value between 0 and 10. I would like to require the user to select a value before going further for I use [disabled] I'd like the user to be able to give a value between 0 and 10. But since I required the user to select something, it it impossible to select 0. In fact, the value is by default 0, so when the user move it (to 1 or more), the button become active but if he comes back to 0 it's impossible to send the result.

  <div *ngFor="let q of questions">
  <h2>{{q.text}}</h2>
  <ion-item >
      <ion-range min='0' max='10' pin="true" [(ngModel)]="q.answer" >
          <ion-label slot="start">0</ion-label>
          <ion-label slot="end">10</ion-label>
      </ion-range>
    </ion-item>
      <ion-button [disabled]='(q.required && !q.answer)' (click)="getAnswer()">Submit</ion-button>
  </div> 

.ts file :

  questions = [
    {
      id: 1,
      text : 'test',
      required: true,
      answer: ''
    }
  ];

  getAnswer() {
    console.log(this.questions);
  }

enter image description here

So Submit is disabled, if I move it, it becomes active but if I come back to 0 it comes back again on disabled... I'd like the user to be able to select 0 but force him to at least make a move...

TD;DR / Expected Behavior

Initially the default value of ion-range is set to 0 and the submit button is disabled. I want to enable the submit button if the user selects a value manually. Even if the user manually sets the value of ion-range to 0.

Upvotes: 1

Views: 137

Answers (1)

arif08
arif08

Reputation: 795

Use a flag to determine if the user touched the ion-range. Set a ionFocus event like this -

  <div *ngFor="let q of questions">
  <h2>{{q.text}}</h2>
  <ion-item >
      <ion-range min='0' max='10' pin="true" [(ngModel)]="q.answer" (ionFocus)="onTouch()">
          <ion-label slot="start">0</ion-label>
          <ion-label slot="end">10</ion-label>
      </ion-range>
    </ion-item>
      <ion-button [disabled]='(q.required && !q.answer && !wasTouched)' (click)="getAnswer()">Submit</ion-button>
  </div> 

And in the typescript file -

...
export class DemoPage {

  ...
  wasTouched = false;

  ...
  touched() {
    this.wasTouched = true;
  }
}

Upvotes: 2

Related Questions