Matt
Matt

Reputation: 186

Toggle the segment using a value from formControl

I have a edit page where I am fetching the values from the database. I am trying to assign the value to ion-segment automatically.

There is my html with formControl and method that's fetches the data from DB:

     this.form = new FormGroup({
                  title: new FormControl(this.task.title,{
                    updateOn: 'blur',
                    validators: [Validators.required]
                  }),
                  description: new FormControl(this.task.description, {
                    updateOn: 'blur',
                    validators: [Validators.required, Validators.maxLength(180)]
                  }),
                  completed: new FormControl(this.task.completed, {
                    validators: [Validators.required]
                  })
                });
      <ion-list-header>Completed</ion-list-header>
            <ion-segment formControlName="completed" value="completed">
              <ion-segment-button  value="true">
                <ion-label>Yes</ion-label>
              </ion-segment-button>
              <ion-segment-button value="false">
                <ion-label>No</ion-label>
              </ion-segment-button>
            </ion-segment>

I managed to transmit the title and description, but the ion-segment is not assigned. Any advice how I can do it?

enter image description here

Upvotes: 1

Views: 1409

Answers (1)

Elias Faraone
Elias Faraone

Reputation: 286

In your case, the value attribute on your ion-segment-button is the string "true" instead of the true value. To achieve what you are looking for you need something like this:

      <ion-list-header>Completed</ion-list-header>
        <ion-segment [value]="form.value.completed? 'yes' : 'no'">
          <ion-segment-button  value="yes">
            <ion-label>Yes</ion-label>
          </ion-segment-button>
          <ion-segment-button value="no">
            <ion-label>No</ion-label>
          </ion-segment-button>
        </ion-segment>

Check out this stackBlitz example.

Upvotes: 3

Related Questions