I have some data which I need to display in the component html and consists of folder names and the files inside the folders.
Here is the data:
data = [
{
"name": "folder1",
"files": [
{
"name": "file1.txt",
},
{
"name": "file2.txt",
}
]
},
{
"name": "folder2",
"files": [
{
"name": "file1.txt",
},
{
"name": "file2.txt",
},
{
"name": "file3.txt",
}
]
}
];
And this is what I'm trying:
<ul *ngFor="let test of data">
<li><h5>{{ test.name }}</h5></li>
<li>{{ test.files.name }}</li>
</ul>
But the result I'm getting is:
folder1
folder2
folder1
folder2
folder1
folder2
The output I need is:
folder1
file1.txt
file2.txt
folder2
file1.txt
file2.txt
file3.txt
How can I fix this so it displays correctly?
I'm not sure how that code is producing exactly that output - are you sure it's the real code? {{ test.files.name }}
would be null, from your example.
Anyway, you are only looping through the folders - to list the content, you need an inner loop for the files. So you can just nest it - something like this.
<ul *ngFor="let test of data">
<li><h5>{{ test.name }}</h5></li>
<ul *ngFor="let file of test.files">
<li>{{ file.name }}</li>
</ul>
</ul>
Note - this is only to show the idea - in reality this would cause a problem if any folder doesn't have a files property, so some checks would be a good idea.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.