我有一个数组数组,我想将其用作目录。重点是根据所有项目的开头字母对它们进行排序。
这是我的项目列表组件的代码:
let itemList = ["Plane","Bird","Boat"];
let directory = [];
for (const item of this.itemList) {
if (this.directory[item.charAt(0).toLowerCase()] == null || undefined) {
this.directory[item.charAt(0).toLowerCase()] = [];
}
this.directory[item.charAt(0).toLowerCase()].push(item);
}
然后我想显示根据首字母排序的所有项目,并且我希望第一个字母显示在以其开头的项目列表上方,就像目录一样。 我在 HTML 中使用以下模板:
<div id="item-list">
<div *ngFor="let entry of directory ; let i = index">
<p>{{i}}</p>
<div *ngFor="let item of entry">
<p>{{item}}</p>
<app-item></app-item>
</div>
</div>
</div>
但是,当我运行应用程序时,我看不到 HTML 中显示的数据。我尝试在几个点打印文本:
<div id="item-list">
<p>Hello</p>
<div *ngFor="let entry of directory ; let i = index">
<p>Hello again</p>
<p>{{i}}</p>
<div *ngFor="let item of entry">
<p>{{item}}</p>
<app-item></app-item>
</div>
</div>
</div>
网页显示“Hello”,但没有“Hello Again”(虽然我认为后者应该打印两次)。但是,无论是运行 ngserve 还是加载页面,都绝对没有错误消息。 我在网上搜索过类似的问题,但似乎没有人在动态显示数组数组时面临同样的困难。
你能告诉我我做错了什么吗?任何帮助将不胜感激。 :)
最佳答案
堆栈 Blitz :https://stackblitz.com/edit/angular-tujusv
目录数组是一个键:值对数组。您可以将 key 存储在不同的数组中并在 html 中访问它们
export class ItemListComponent implements OnInit {
alphabet: string[];
directory = [];
dirArr =[];
itemList = ["Plane", "Bird", "Boat"];
constructor() {
this.alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
}
ngOnInit() {
this.itemList.sort();
for (const item of this.itemList) {
if (this.directory[item.charAt(0).toLowerCase()] == null || undefined) {
this.directory[item.charAt(0).toLowerCase()] = [];
}
this.directory[item.charAt(0).toLowerCase()].push(item);
console.log(this.directory);
this.dirArr = Object.keys(this.directory);
console.log(this.dirArr)
}
console.log(this.directory['p']);
}
}
HTML:
<div id="item-list">
<p>Hello</p>
<div *ngFor="let entry of dirArr ; let i = index">
<p>Hello again</p>
<p>{{i}}</p>
<p>{{entry}}</p>
<p>{{directory[entry]}}</p>
<div *ngFor="let item of directory[entry]">
<p>{{item}}</p>
</div>
</div>
</div>
关于javascript - *ngFor 指令不适用于数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127547/