Gerald Muller
Gerald Muller

Reputation: 23

Setting an input value on page load in Angular

I want to set the value of my input value to 1 when the the page is loaded. But the box is empty when I execute the code.

<tr *ngFor="let item of cartItems; let i=index">
    <td class="cart_product"><a href="#"><img class="img-fluid" [src]="item.image" alt=""></a></td>
    <td class="cart_description">
        <h3 class="product-name"><a href="#">{{item.title}} </a></h3>
        <h6><strong><span class="mdi mdi-approval"></span> Available in</strong> - 500 gm</h6>
    </td>
    <td class="availability in-stock"><span class="badge badge-success">Checkers</span></td>
    <td class="price"><span>${{item.price}}</span></td>
    <td class="qty">
        <div class="input-group">
            <span class="input-group-btn"><button [disabled]="cartItems[i].quantity == 0" class="btn btn-theme-round btn-number" type="button" (click)="reduceQuantity(i)">-</button></span>
            <input type="text" max="10" min="1" value="1" class="form-control border-form-control form-control-sm input-number" name="quantity"  [(ngModel)]="cartItems[i].quantity">
            <span class="input-group-btn"><button class="btn btn-theme-round btn-number" type="button" (click)="addQuantity(i)">+</button>
            </span>
        </div>
    </td>
    <td class="price"><span>{{getQuantity(i)}}</span></td>
    <td class="action">
        <a class="btn btn-sm btn-danger" data-original-title="Remove" href="#" title="" data-placement="top" data-toggle="tooltip"><i class="mdi mdi-close-circle-outline"></i></a>
    </td>
</tr>

enter image description here

Upvotes: 0

Views: 2453

Answers (2)

Naresh J
Naresh J

Reputation: 2127

You used bi-directional binding on your input:

[(ngModel)]="cartItems[i].quantity"

Ideally it should set default value as 0 in your backend else you can set it's value to 0 in your component.ts file like setting values in cartItem:

cartItems.map(function(cartItem) { 
    if(!cartItem.quantity) {
        cartItem.quantity = 0;
      }
    });

Upvotes: 1

Nam Dao
Nam Dao

Reputation: 409

Even though you've set the value property of the input to 1, you are seeing an empty box because cartItems[i].quantity is undefined. Therefore the ngModel quickly changes that box to empty.

Upvotes: 1

Related Questions