我正在 Ionic 5 和 Angular 9 中做一个应用程序。
我有一个单选组,其中包含通过 HTTP 请求获取的选项,我想以编程方式将其中一个选项设置为选定。
组件:
options: {id: string, description: string}[] = [];
optionSelected = null;
constructor(
private service: MyService,
) {
}
ngOnInit() {
this.service.getOptions()
.pipe(first())
.subscribe(res => {
this.options = res;
// Setting the option selected by default.
this.optionSelected = {id:"001", description:'This is selected by default'};
});
}
trackById(index: number, option: any): string {
return option.id;
}
模板:
<ion-list>
<ion-radio-group (ionChange)="optionSelected = $event.target.value" [(ngModel)]="optionSelected">
<ion-item *ngFor="let a of options; trackBy: trackById">
<ion-radio slot="start" [value]="a"></ion-radio>
<ion-label class="ion-text-wrap"><h3>{{a.description}}</h3></ion-label>
</ion-item>
</ion-radio-group>
</ion-list>
当我获取数据时,我分配了我想要选择的对象,但是,它没有在单选组中选择。
我的目标是在获取数据时以编程方式检查单选组中的单选按钮。
最佳答案
对象比较不同于其他类型的比较。
示例:
字符串与字符串比较:
console.log("a"=== "a");//正确
对象与对象比较;
console.log({a:1,b:2,c:3} === {a:1, b:2, c:3});//错误
,所以我认为你的错误是将对象
绑定(bind)为选项的值。因为,当它与 ===
运算符比较对象时,它返回 false。
解决问题的方法:
您需要绑定(bind)您的实体的id。
模板:
<ion-radio-group [(ngModel)]="optionSelected">
<ion-item *ngFor="let a of options; trackBy: trackById">
<ion-radio slot="start" [value]="a.id"></ion-radio>
<ion-label class="ion-text-wrap"><h3>{{a.description}}</h3></ion-label>
</ion-item>
</ion-radio-group>
组件:
ngOnInit() {
this.service.getOptions()
.pipe(first())
.subscribe(res => {
this.options = res;
// Setting the option selected by default.
this.optionSelected = res[0].id; // example
});
}
并且您不需要 (ionChange) 函数,因为 [(ngModel)]
是双向绑定(bind),因此当它更改时,您的变量也会更改。如果无论如何您需要在更改时执行某些操作,您可以使用 ngModelChange 事件,如下所示:
<ion-radio-group (ngModelChange)="changed()" [(ngModel)]="optionSelected">
</ion-radio-group>
最后,您将在 optionSelected
变量中获得所选选项的 ID。如果需要完整找到选项实体:
const selectedOption = this.options.find(opt => opt.id === optionSelected);
关于angular - 在 Ionic 5 和 Angular 9 中以编程方式设置单选按钮组中的选中单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62677861/