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

fcg9iug3  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我想在我的html文件中使用“for”循环创建UI,这样就不需要编写所有的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>

我该怎么做呢?

ovfsdjhp

ovfsdjhp1#

看一下关于结构指令的文档。你也可以看一个tour of heroes来了解Angular 指令的基本原理。
重复“行业”

<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>

相关问题