Search code examples
javascriptangulartwitter-bootstrapaccordionngfor

Dynamically set class or id using index of ngFor loop


So I am trying to create a collapse (accordion) in Bootstrap 4 using Angular. I would love to be able to create almost the entire thing using an ngFor loop.

So far I have this:

<div class="row">
  <div class="col-lg-6">
    <div id="accordion" role="tablist" aria-multiselectable="true">
      <div class="card" *ngFor="let environment of environments; let i = index;">
        <div class="card-header" role="tab" id="headingi">
          <h5 class="mb-0">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapsei" aria-expanded="false" aria-controls="collapsei">
              Number: {{i}}
            </a>
          </h5>
        </div>

        <div id="collapseOne" class="collapse show" role="tabpanel" aria-labelledby="headingOne">
          <div class="card-block">
            <div *ngFor="let name of uniqueNames; let j = index" class="card infoBox">
              <p>this is accordion {{i}}, section: {{j}}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

What I am trying to do is use "let i = index" to set the id and class names needed to make the accordion know what to do when certain links are clicked. So ideally the first accordion section would have class and id of collapse0/heading0 and the next would have id and class of collapse1/heading1 etc.

However, the previous code must not be working because all the accordions and their headers show up and do nothing when clicked on. It does generate the correct number, show all the right headers, and the bodies associated with them.

Any help? thanks!


Solution

  • You can do it this way also

    id="collapse{{i}}" class="heading{{i}}" attr.aria-controls="heading{{i}}"
    

    and the fact that aria- attributes are being handled another way in angular you have to prefix them with attr.. In your example should that be attr.aria-controls="heading{{i}}".