Search code examples
angularclarity

Clr-accrodion not working as expected with ngFor


I have been trying to find a solution on accordion on clarity v5 framework in an angular 10 project but without any success. The issue that I have is:

in component.ts:

info = [{name: '1'}, {name: '2'}];

getInfo(): any[] {
 return [{name: '1'}, {name: '2'}];
}

in component.html:

First

<clr-accordion>
    <clr-accordion-panel  *ngFor="let i of getInfo()">
        <clr-accordion-title>Item {{i.name}}</clr-accordion-title>
        <clr-accordion-content *clrIfExpanded>Content 1</clr-accordion-content>
    </clr-accordion-panel>
</clr-accordion>

Second

<clr-accordion>
    <clr-accordion-panel  *ngFor="let i of info">
        <clr-accordion-title>Item {{i.name}}</clr-accordion-title>
        <clr-accordion-content *clrIfExpanded>Content 1</clr-accordion-content>
    </clr-accordion-panel>
</clr-accordion>

The Second is working as expected. However the first although it shows the items on click it doesn't open the accordion. Any ideas?


Solution

  • in first example on every change detection iteraton new array is created. because of that, the item you clicked no longer exists, and instead of it, new element is created, which is not opened. to kinda fix it you can provide trackBy function *ngFor="let i of info; trackBy: trackByName" trackBy(i, obj){return obj.name}, so angular would associate old element with the new one, but it seems to me that just saving array as a field is better solution here.