Search code examples
cssionic4

ionic 4 make ion-item transparent depending upon selected value


If selected value using <select> is greater than the value in the database, I want to make that particular ion-item transparent or blur. For that, I have a property called disabled. But I can't dynamically make ion-item transparent. Thank you in advance

  onChange(new_quantity,object, stock  ) {
    let stocks = stock

     for(let i=0; i<stocks.length; i++) {
            if(new_quantity > stocks[i].RemainingQuantity){


              console.log(new_quantity)
              console.log(object.quantity)
              console.log(stocks[i].RemainingQuantity)

              object.disabled = true
              console.log("quantity not available")

              this.presentAlert()
            }
    }
}

html

<ion-list>
    <ion-item *ngFor="let p of cart ;  let i=index" class="ion-text-wrap">

            <ion-grid>

              <div class="ion-text-end" *ngIf="p.disabled">
                <ion-label color="tertiary">Out of stock</ion-label>
              </div>

     <select style="max-width:50%;" (change)="onChange($event.target.value, p, p.product.stocks) " [value]=p.quantity  > 

      <option  [ngValue] = "q" *ngFor ="let q of quantity" >{{q}}</option>
      </select>
      </ion-grid>

        </ion-item>
</ion-list>

Solution

  • You can simplify your code by just passing the index of the cart to check the products stock. If you get the value of the ion-select with ngModel, you can access that value directly in the function without passing it in.

    There we loop your selected products stock. If the remainingQuantity is less than your productQuantity, the cart is disabled. This will add a new css class item-disabled to your item, which sets the background to transparent.

    Html

    <ion-list>
      <ion-item *ngFor="let c of cart; let i=index" class="ion-text-wrap" [ngClass]="{ 'item-transparent': c.disabled  }">
        <ion-grid>
          <div class="ion-text-end" *ngIf="c.disabled">
            <ion-label color="tertiary">Out of stock</ion-label>
          </div>
          <ion-select style="max-width:50%;" [(ngModel)]="productQuantity" (ionChange)="checkIfProductIsOutOfStock(i)" value="c.quantity"> 
            <ion-select-option value="quantity" *ngFor="let quantity of c.quantity">{{ quantity }}</ion-select-option>
          </ion-select>
        </ion-grid>
      </ion-item>
    </ion-list>
    

    Ts

    productQuantity: number;
    
    checkIfProductIsOutOfStock(index: number) {
      const stocks = this.cart[index].products.stocks;
    
      stocks.forEach((stock: object) => {
        if (this.productQuantity > stock['RemainingQuantity'] {
          this.cart[index].disabled = true;
        }
      });
    }
    

    Css

    .item-transparent {
      --background: transparent;
    }