Home > Software design >  TypeScript For loop for nested array in html file
TypeScript For loop for nested array in html file

Time:01-14

I want to create UI using "for" loop inside my html file, so that will not need to write all the html. This is my model class

export class Industries 
{
  alphaIndex: string = '';
  industries: Array<string> = [];

  constructor(alphaIndex: string, industries: string[]) {
    this.alphaIndex = alphaIndex;
    this.industries = industries; 
  }
}

This data I have added in above model class from component class

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);
    .....
}

This UI want to be repeated

<div >
 <div >
    <a href="#" data-toggle="dropdown">Item.alphaIndex
        <i ></i>
    </a>
    <div >
        <a href="#" >Item.Data</a>
    </div>
 </div>
</div>

How can I do that ?

CodePudding user response:

Take a look to the docs about structural directive. You can also take a tour of heroes to understand the basic of Angular.

Just iterate over 'industries'

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

Update there're many errors in before code, we can use

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

See stackblitz

OR

<div *ngFor="let item of industries" >
    <div >
        <a data-toggle="dropdown">{{item.alphaIndex}}
            <i ></i>
        </a>
        <div >
            <a *ngFor="let data of item.industries" >{{data}}</a>
        </div>
    </div>
</div>
  • Related