Search code examples
angularangular-loopback

Get response data without loop angular2 error


In my angular2 project I am trying to get the value of email id from the object array. There is only 1 object I don't want to use loop. So I am trying to get the value using

{{customers[0].customer_email}}

which doesn't work but below code work.

    <ion-item *ngFor="let customer of customers">
        <ion-label fixed>Email</ion-label>
        <ion-input type="text" value="{{customer.customer_email}}"></ion-input>         
    </ion-item>

Any idea how do I use it without loop ?


Solution

  • Simply omit the ngFor and index your customers response directly:

    <ion-item>
        <ion-label fixed>Email</ion-label>
        <ion-input type="text" value="{{customers[0].customer_email}}"></ion-input>         
    </ion-item>
    

    If you get an array out of bounds exception (which is caused by trying to apply an indexer [0] to an array without any elements), apply an ngIf to your item to prevent it from rendering until the data is loaded:

    <ion-item *ngIf="customers && customers.length">
        <ion-label fixed>Email</ion-label>
        <ion-input type="text" value="{{customers[0].customer_email}}"></ion-input>         
    </ion-item>