You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套在async容器中的Ionic Segment动态值无法正常工作的原因

问题:嵌套在async容器中的Ionic Segment无法正确初始化高亮

开发包含多个<ion-segment>元素的页面时,发现部分嵌套在async容器中的<ion-segment>无法正确初始化——选中的<ion-segment-button>不会按预期高亮,只有硬编码初始值才能正常显示。

HTML文件

<ion-header>
  <ion-toolbar>
    <ion-title>Ionic Segment Bug Test</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-segment
    [value]="segmentA$ | async"
    (ionChange)="updateSegmentA($event.detail.value!)"
  >
    <ion-segment-button value="A-1">
      <ion-label>segment A-1</ion-label>
    </ion-segment-button>
    <ion-segment-button value="A-2">
      <ion-label>segment A-2</ion-label>
    </ion-segment-button>
  </ion-segment>
  <p class="ion-text-center">segment A value = "{{ segmentA$.value }}"</p>
  <hr />
  <div *ngIf="observable$ | async as dataSource; else noData">
    <ion-segment
      [value]="segmentB"
      (ionChange)="updateSegmentB($event.detail.value!)"
    >
      <ion-segment-button value="B-1">
        <ion-label>segment B-1</ion-label>
      </ion-segment-button>
      <ion-segment-button value="B-2">
        <ion-label>segment B-2</ion-label>
      </ion-segment-button>
    </ion-segment>
    <p class="ion-text-center">segment B value = "{{ segmentB }}"</p>
    <hr />
    <ion-segment value="default">
      <ion-segment-button value="default">
        <ion-label>Default</ion-label>
      </ion-segment-button>
      <ion-segment-button value="segment">
        <ion-label>Segment</ion-label>
      </ion-segment-button>
    </ion-segment>
  </div>

  <ng-template #noData>
    <p class="ion-text-center">No data to display</p>
  </ng-template>
</ion-content>

TS文件(片段)

segmentA$ = new BehaviorSubject<string>('A-1');
observable$ = new Observable<any>();
segmentB = 'B-1';

constructor() {
  this.fetchData();
}

updateSegmentA(value: SegmentValue) {
  this.segmentA$.next(value as string);
}

updateSegmentB(value: SegmentValue) {
  this.segmentB = value as string;
}

private fetchData() {
  let option: string;
  this.observable$ = this.segmentA$.pipe(
    distinctUntilChanged(),
    tap((o) => (option = o)),
    delay(1000),
    map(() => option),
  );
}

已尝试的解决方案:

  • 使用[(ngModel)]绑定值
  • 结合async管道使用BehaviorSubject

以上两种方法均未解决问题。

内容的提问来源于stack exchange,提问作者Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:58:25