Firas M'rabet
Firas M'rabet

Reputation: 21

Display data from list with index using angular 2

How to display data in HTML from a list without using *ngFor for example like This list[5].name

I tried this :

PostList[5].{{def}}

{{PostList[5].def}}

Upvotes: 0

Views: 1333

Answers (2)

{{PostList[5].def}} should work if you have this.PostList variable in your component (and it is an array which 6th element is an object with def)

Upvotes: 0

martinomburajr
martinomburajr

Reputation: 1265

In your case {{PostList[5].def}} works.

Assuming you have your component initializing a simple list with an Object

export class AppComponent  {
  list = new Array<{name: string}>();

  constructor() {
    this.list[0] = {"name": "Martin"}
    this.list[1] = {"name": "Emma"}
    this.list[2] = {"name": "Daisy"}
  }
}

and if you want to get Emma, your view will therefore be.

<p>
  {{list[1].name}}
</p>

//Output Emma

Update I would like to add that, if for instance the list doesnt have a certain index e.g index greater than 2, or the value is null. You can use the ? operator in html to be safe.

Therefore {{list[3]?.name}} wont crash your app, even though the output is null.

Upvotes: 2

Related Questions