1

How would I get data from an Array in Ionic 3 without having to use ngFor?

For example, this works

  <ion-item-sliding *ngFor="let user of users">
    <ion-item>
      <ion-grid>
        <ion-row>
          <ion-col>
            <strong>Name:</strong>
          </ion-col>
          <ion-col>
            {{user.name}}
          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item> 
    <ion-item-options side="left">
      <button ion-button (click)="delete()">
        <ion-icon name="ios-trash"></ion-icon> Delete
      </button>
    </ion-item-options>
  </ion-item-sliding>

But my users array only has 1 row, so how can I access the data without having to loop through the array using *ngFor?

Something like this?

{{users[0].id}}

Thanks

1
  • Yes, you can use {{users[0].id}} Commented Mar 8, 2018 at 15:56

1 Answer 1

1

As Alex said, you can use the example provided.

If you are unsure if the array has any objects, you can do something like {{ users.length > 0 ? users[0].id : '' }} or if you have many fields to display:

<div *ngIf="users.length > 0">
  <span>{{ users[0].id }}</span>
<div>

If you need to also check for undefined or null, just add that to the check. F.ex.:

<div *ngIf="users !== undefined && users !== null && users.length > 0">
  <span>{{ users[0].id }}</span>
<div>
Sign up to request clarification or add additional context in comments.

2 Comments

this doesn't seem to work for me? it returns undefined is not an object (evaluating '_co.users[0].id'), but works in the ngFor loop? Sorry if i'm missing something obvious, i'm fairly new to angular and ionic!
Well either _co, users, or users[0] is undefined. If you find out which you can check it. Typically it is undefined before you get the data, thats why it fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.