Hello guys,
How can I get a specific data object from data array and use it in HTML?
{
name: "object01",
description: "this is item 01",
id: "1"
},
{
name: "object02",
description: "this is item 02",
id: "2"
},
{
name: "object03",
description: "this is item 03",
id: "3"
},
{
name: "object04",
description: "this is item 04",
id: "4"
}
For example, I want to get id number of fourth item and use it in html.
<h4>{{ item.object04.id }}</h4>
or just want to get description of fourth item.
How can I do this without using *ngFor directive?
Thanks,
Withuot ngFor you need to save the data as object
{
object01: {
name: "object01",
description: "this is item 01",
id: "1"
},
object02: {
name: "object02",
description: "this is item 02",
id: "2"
},
object03: {
name: "object03",
description: "this is item 03",
id: "3"
},
object04: {
name: "object04",
description: "this is item 04",
id: "4"
}
}
1 Like
if your array has a name like “myArray”, then you could bind your template to myArray[3].id (3 here as index of array starts with 0). But that is if you not using ngFor directive.
1 Like
Thanks but that didn’t work… I’m using data array in this way:
{
"items": [
{
"name": "item 01",
"description": "this is item 01",
"id": "1"
},
{
"name": "item 02",
"description": "this is item 02",
"id": "2"
},
{
"name": "item 03",
"description": "this is item 03",
"id": "3"
},
]
}
I can’t add below type of data object inside the array…
object03: {
name: "object03",
description: "this is item 03",
id: "3"
},
object04: {
name: "object04",
description: "this is item 04",
id: "4"
}
Any other advice would be appreciated…
Again you doing the same mistake don’t use as array use as object
And in your html ngFor you need to use pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'keys',
})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
return Object.keys(value);
}
}
HTML:
<div *ngFor="let key of items | keys">
<div>{{items[key].id}}</div>
<div>{{items[key].description}}</div>
</div>
1 Like