更改离子列表项上的复选框状态点击



我有一个列表,每行都有一个复选框。我希望每当我点击复选框时,对象都需要根据复选框的状态进行相应的更新,但使用下面的复选框时我会出现异常,如无法设置未定义或空引用的属性">checked">

.ts:

export class Custom{
name: string
empoloyeeID: number
checked:boolean
}
export class CheckboxListPage {
contacts:Array<Custom> = [];
constructor(public navCtrl: NavController, public navParams: NavParams) {
let customObj1 = new Custom();
customObj1.empoloyeeID = 1;
customObj1.name = "Ramakrishna"; 
let customObj2 = new Custom();
customObj2.empoloyeeID = 2;
customObj2.name = "Ramakrishna2"; 
this.contacts.push(customObj1);
this.contacts.push(customObj2);
}
updateCucumber(contact){
this.contacts[contact.id].checked = !contact.checked;
}

.html:

<ion-content padding>
<ion-list>
<ion-item *ngFor="let contact of contacts" (click)="update(contact)">
<!-- <ion-avatar item-start>
<img src="imgs/img_snow.jpg">
</ion-avatar> -->
<ion-avatar item-left>
<img src="https://ionicframework.com/dist/preview-app/www/assets/img/marty-avatar.png">
</ion-avatar>
<h2>{{contact.name}}</h2>
<p *ngIf="contact.id===1;else other_content">your if block</p>
<ng-template #other_content><p>your else block1</p></ng-template>
<ion-row>
<ion-col col-2 no-padding no-margin>
<ion-item no-padding no-margin no-lines>
<ion-checkbox [(ngModel)]="contact.checked" (ionChange)="updateCucumber(contact)"></ion-checkbox>
</ion-item>
</ion-col>
<ion-col col-10 no-padding no-margin>
<ion-item no-padding no-margin no-lines>
Agree to <a target="_blank" href="http://www.terms-of-service.com">Terms of Service</a>
and <a target="_blank" href="http://www.privacy-policy.com">Privacy Policy</a>.
</ion-item>
</ion-col>
</ion-row>
</ion-item>

</ion-list>
</ion-content>

不确定我是否答对了,但如果你想在每次点击复选框时更新相应的联系人对象,你可以尝试这样的方法:

export class CheckboxListPage {
contacts = [
{
name: "Ramakrishna",
id: 1,
selected: false
},
{
name: "Ramakrishna2",
id: 2,
selected: false
}
]
constructor(public navCtrl: NavController,
public navParams: NavParams) {}
updateCucumber(contact) {
contact.selected = !contact.selected;
}
}

你的HTML基本保持不变:

<ion-checkbox (ionChange)="updateCucumber(contact)"></ion-checkbox>

最新更新