TypeScript For循环在html文件中嵌套数组



我想创建一个使用"for"在我的HTML文件内循环,这样就不需要编写所有的HTML。这是我的模型类

export class Industries 
{
alphaIndex: string = '';
industries: Array<string> = [];
constructor(alphaIndex: string, industries: string[]) {
this.alphaIndex = alphaIndex;
this.industries = industries; 
}
}

我从组件类

中添加到上述模型类中的数据
industries: Array<Industries> = [];

constructor() {
this.getIndustryData();

}
getIndustryData()
{
let recordAE = new Industries ('A-E',['Aerospace & Defense','Automotive','Banking', 'Capital Market','Enterprise Strategy']);
this.industries.push(recordAE);
let recordFO = new Industries ('FO',['Forest Products & Chemicals', 'Industrial','Insurance','Mining','Metals']);
this.industries.push(recordFO);
.....
}

这个UI需要重复

<div class="col-md-2">
<div class="nav-item dropdown">
<a href="#" data-toggle="dropdown">Item.alphaIndex
<i class="bi bi-chevron-right"></i>
</a>
<div class="dropdown-menu">
<a href="#" class="dropdown-item">Item.Data</a>
</div>
</div>
</div>

我该怎么做呢?

看一下有关结构指令的文档。你也可以通过浏览英雄列表来了解Angular的基础知识。

只遍历'industries'

<div *ngFor="let industry of industies">
<div class="nav-item dropdown">
<!--see that here you use "industry"
use "interpolation" to get the value
-->
<a href="#" data-toggle="dropdown">{{industry.alphaIndex}}
<i class="bi bi-chevron-right"></i>
</a>
<!--here iterate over industry.Data-->
<div *ngFor="let data of industry.data" class="dropdown-menu">
<!--again use interpolation-->
<a href="#" class="dropdown-item">{{data}}</a>
</div>
</div>
</div>

前面的代码有很多错误,我们可以使用

<div class="row gx-0">
<div class="col-2" *ngFor="let industry of industries; let i = index">
<button 
(click)="menu.classList.toggle('show')"
class="btn btn-secondary dropdown-toggle"
type="button"
data-bs-toggle="dropdown"
aria-expanded="false">
{{ industry.alphaIndex }}
</button>
<ul
#menu
class="dropdown-menu">
<li *ngFor="let data of industry.industries">
<a class="dropdown-item" href="#">{{ data }}</a>
</li>
</ul>
</div>
</div>

看到stackblitz

<div *ngFor="let item of industries" class="col-md-3">
<div class="nav-item dropdown">
<a data-toggle="dropdown">{{item.alphaIndex}}
<i class="bi bi-chevron-right"></i>
</a>
<div class="dropdown-menu">
<a *ngFor="let data of item.industries" class="dropdown-item">{{data}}</a>
</div>
</div>
</div>

最新更新