Ionic中点击按钮后禁用已选中复选框问题求助
解决Ionic配置文件组创建后选中项不可点击/消失的问题
嘿,我来帮你搞定这个问题!你想要实现的是用户选完配置文件创建组后,让已选中的选项要么消失,要么不能再被点击对吧?之前把profiles[i]设为0的做法确实不太理想,咱们换两种更靠谱的方式来实现:
方案一:创建组后直接移除已选中的配置文件(让它们从列表消失)
这个思路是筛选出用户选中的配置文件,把它们加入组列表,然后从原profiles数组里删掉这些项,这样页面上就看不到它们了。
修改后的HTML代码
<ion-list> <ion-item *ngFor="let profile of profiles; let i = index"> <ion-label>{{profile.name}}</ion-label> <ion-checkbox color="dark" [(ngModel)]="profile.selected"></ion-checkbox> </ion-item> </ion-list> <button ion-button full (click)="addGroup()">Add group</button>
修改后的TS代码
import { AlertController } from 'ionic-angular'; // ... profiles = []; groupList = []; constructor(private alertCtrl: AlertController) {} addGroup(){ // 第一步:筛选出用户选中的配置文件 const selectedProfiles = this.profiles.filter(profile => profile.selected); // 第二步:把选中的配置文件添加到组列表里 this.groupList.push(...selectedProfiles); // 第三步:从原profiles数组移除已选中的项,页面上就会自动消失 this.profiles = this.profiles.filter(profile => !profile.selected); // 弹出创建成功的提示 const alert = this.alertCtrl.create({ title: 'Group created!', buttons: ['OK'] }); alert.present(); }
方案二:让已选中的配置文件保留在列表,但不可再点击
如果你不想让选中的项消失,只是想让它们不能再被选择,可以给每个配置文件加一个disabled属性,用来控制复选框的禁用状态。
修改后的HTML代码
<ion-list> <ion-item *ngFor="let profile of profiles; let i = index"> <ion-label>{{profile.name}}</ion-label> <ion-checkbox color="dark" [(ngModel)]="profile.selected" [disabled]="profile.disabled"></ion-checkbox> </ion-item> </ion-list> <button ion-button full (click)="addGroup()">Add group</button>
修改后的TS代码
import { AlertController } from 'ionic-angular'; // ... profiles = []; groupList = []; constructor(private alertCtrl: AlertController) {} addGroup(){ // 筛选出选中的配置文件 const selectedProfiles = this.profiles.filter(profile => profile.selected); // 添加到组列表 this.groupList.push(...selectedProfiles); // 标记这些选中的配置文件为禁用,同时可以取消选中状态 selectedProfiles.forEach(profile => { profile.disabled = true; profile.selected = false; // 可选:如果想取消选中状态的话 }); // 弹出提示 const alert = this.alertCtrl.create({ title: 'Group created!', buttons: ['OK'] }); alert.present(); }
为什么原来的方法不好?
你之前把profiles[i] = 0的做法会让数组里混入非对象类型的元素,后续*ngFor遍历的时候很容易出现错误,而且逻辑上也不够清晰。上面两种方法都是基于操作数组元素的属性或者直接过滤数组,更符合Angular/Ionic的开发习惯。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

