Helloo !
i would use a json files in my angular-app.
I have a local json file ‘client.json’
{
"T001": {
"name": "admin",
"type": "adm",
"id": "1",
"class": "viewer",
},
"T002": {
"name": "Customer",
"type": "usr",
"id": "2",
"class": "viewer",
},
"T003": {
"name": "DB450",
"type": "air",
"id": "3",
"class": "gateway",
},
"T004": {
"name": "DB620",
"type": "air",
"id": "4",
"class": "gateway",
}
}
Actually, i could read this file and i got access to the name of object (object of object) — T003.name for example and using console.log to display the result but this is not what i’m looking for because i can’t use this variable into html template.
import { Component, OnInit } from '@angular/core';
import * as tunnelsData from '../data/client.json'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
objects: any;
ngOnInit(): void {
this.objects = (tunnelsData as any).default;
console.log(this.object);
}
}
I’m looking for loads this file into a variable, then using this variable on a html template with ngfor like this :
<my-app *ngFor="let T of objects"
[tunnel]="T"
[name]="T.name"><my-app>
tunnel and name are two variables of my second component
To display at the end an example like this :
Tunnel : T001 (which the first object of my file)
Name : admin (which an object of the first object)
.
.
.
I hope it’s clear for you.
any idea please ?
Thank you.
2
Answers
Generaly, angular does not support iterating over objects in ngFor.
Check your browser’s dev tools console. There should be an error.
You can use pipe in ngFor to make it work KeyValuePipe.
For more details check this thread.
And to display the key (eg."T001"), you would need to pass it too.
The only problem is that you don’t have an
array
in yourjson
data. you have this data as anobject
And in your
html
you are trying to loop through your elements withngFor
. SongFor
directive always expects anarray
to loop inhtml
.So the simple solution you can have is that in your component you can do like this
app.component.ts
And inside of your
html
you can do like thisWhat i am doing here is that first i am getting all of the keys of your
object
as anarray
and then i am iterating over the array ofkeys
. And inhtml
i am accessing the individualobject
by it’s key name which is coming fromngFor
loop.