带有if条件和布尔值的Typescript for循环



我有一个for循环,生成2个按钮和两个按钮显示或隐藏基础上的每一行的条件。出于某种原因,我使用布尔值,满足一个条件,然后所有行都受到影响,但我只希望特别受到影响。下面是我的代码。该程序是用离子型Angular编写的。

前端HTML文件

<ion-list *ngFor="let ml of miqaatITS">
<ion-item>
<ion-label><b>{{ml.event}}</b><br>{{ml.date}}<br>{{ml.time}}</ion-label>
<ion-button color="dark" [routerLink]="['/home/Allocation']" *ngIf="isPass">VIEW PASS</ion-button>
<ion-button color="dark" fill="outline" *ngIf="!isPass" disabled>NO PASS</ion-button>
<ion-button color="danger" >CANCEL PASS</ion-button>
</ion-item>
</ion-list>

。ts文件

isPass = false;
feedData() {
console.log(this.authUser);
this.postData.user_id = this.authUser.user_id;
this.postData.token = this.authUser.token;
this.postData.itsnumber = this.authUser.itsnumber;
if (this.postData.user_id && this.postData.token) {
this.miqaat.miqaatITSData(this.postData).subscribe(
(res: any) => {
console.log(res);
for(var pass of res.miqaatITS){
console.log(pass.allocation == 1);
if(pass.allocation == 1) {
this.isPass = !this.isPass;
}
}
this.miqaat.changeMiqaatData(res.miqaatITS);
},
(error: any) => {
this.toastService.presentToast('Network Issue.');
}
);
}
}

请通知

在本例中,isPass是单个布尔值。它将取for循环中的最后一个值。您需要做的是,为每一行引入一个新变量,然后应用它。不是单个的ispass,而是所有行的ispass。像这样:

************  In .ts code ********
console.log(res);
for(var pass of res.miqaatITS){
let pass['isPass'] = false;
console.log(pass.allocation == 1);
if(pass.allocation == 1) {
pass['isPass'] = !pass['isPass'];
}
********* in html ********
<ion-button color="dark" fill="outline" *ngIf="!!ml.isPass" disabled>NO PASS</ion-button>
Note: you need two exclamation marks, because it'll check for null value too. 

您可以这样使用

Html代码。

<ion-list *ngFor="let ml of miqaatITS">
<ion-item>
<ion-label><b>{{ml.event}}</b><br>{{ml.date}}<br>{{ml.time}}</ion-label>
<ion-button color="dark" [routerLink]="['/home/Allocation']" *ngIf="ml.allocation">VIEW PASS</ion-button>
<ion-button color="dark" fill="outline" *ngIf="!ml.allocation" disabled>NO PASS</ion-button>
<ion-button color="danger" >CANCEL PASS</ion-button>
</ion-item>
</ion-list>

。ts代码

miqaatITS:any;
isPass = false;
feedData() {
console.log(this.authUser);
this.postData.user_id = this.authUser.user_id;
this.postData.token = this.authUser.token;
this.postData.itsnumber = this.authUser.itsnumber;
if (this.postData.user_id && this.postData.token) {
this.miqaat.miqaatITSData(this.postData).subscribe(
(res: any) => {
console.log(res);
this.miqaatITS = res.miqaatITS

this.miqaat.changeMiqaatData(res.miqaatITS); // Dont know why you have used this. Remove if this is it not usefull.
},
(error: any) => {
this.toastService.presentToast('Network Issue.');
}
);
}
}

最新更新