我正在处理一个包含多个<ion-segment>
个元素的页面,其中一些元素嵌套在async
个容器中.
除非对初始值进行了硬编码,否则这些值不会被正确地初始化,并且所选的<ion-segment-button>
不会像它应该的那样被突出显示.
请参见下面的示例:
HTML file
<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 file (extract)
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),
);
}
请参阅GitHub或StackBlitz上的完整示例.
我试着用[(ngModel)]
或BehaviorSubject
加async
管,但都没有用.