我需要帮助从生成的单选按钮列表中预选第一个单选按钮,如果用户选择不同的单选按钮,可以更改这些单选按钮...
我的尝试返回了这个错误:
TypeError: Cannot read properties of undefined (reading '0')
交货日期.model.ts
export interface DeliveryDates {
color: string;
date: string;
date_name: string;
}
cart.page.ts代码:
export class CartPage implements OnInit, OnDestroy {
dates: DeliveryDates[];
selectedValue: any;
private datesSubscription: Subscription;
constructor() {
}
ngOnInit() {
this.getDeliveryDates();
this.selectedValue = this.dates[0].date;
}
getDeliveryDates() {
this.datesSubscription =
this.cartService.getDeliveryDates().subscribe(
data => {
this.dates = data;
},
error => {
console.log('Error', error);
});
}
}
cart.page.html
<ion-list class="dates-list">
<ion-radio-group value="{{dates[0]}}" [(ngModel)]="selectedValue">
<ion-item *ngFor="let datum of dates;let i = index" (click)="modal.dismiss()">
<ion-icon name="today-outline"></ion-icon>
<ion-label class="{{datum.color}}">{{datum.date_name}} {{ datum.date }}</ion-label>
<ion-radio slot="end" value="{{ datum.date }}"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
你为什么不能试试这段代码??您正在尝试在启动时设置值。但是在获取值之前分配的值。
export class CartPage implements OnInit, OnDestroy {
dates: DeliveryDates[];
selectedValue: any;
private datesSubscription: Subscription;
constructor() {
}
ngOnInit() {
this.getDeliveryDates();
}
getDeliveryDates() {
this.datesSubscription =
this.cartService.getDeliveryDates().subscribe(
data => {
this.dates = data;
(this.dates.length>0)?this.selectedValue = this.dates[0].date:false;
},
error => {
console.log('Error', error);
});
}
}