Programmatically change active segment from controller (resolved)

Can I am trying with no success to change the active segment from controller.

By setting the model value in controller the active segment does not change, which I assumed would be default behaviour.

I tried to use reference to the ion-segment-button and trigger click in controller but the native element in not accessible as the ion-segment-button directive strips the reference.

It does for me.

<ion-segment [(ngModel)]="segment">
    <ion-segment-button value="apple">
      apple
    </ion-segment-button>
    <ion-segment-button value="banana">
      banana
    </ion-segment-button>
  </ion-segment>

  <button ion-button (click)="flipSegment()">flip segment</button>

  segment: string;

  flipSegment(): void {
    if (this.segment === 'apple') {
      this.segment = 'banana';
    } else {
      this.segment = 'apple';
    }
  }

Works exactly as one would expect.

2 Likes

Well, I wonder if there is some race issue. I will revisit the code and update here. Thanks for the prompt reply.

It worked, it was one of those silly copy paste that we all have had. Thanks for reasserting that it works forcing me to look at each line of code to find the silly mistake

1 Like

Works flawless in V4 too. Just used this in my project. Thx. Even after so long.