Javascript – Angular2 Collapse another Component’s

angularcollapsehtmljavascripttwitter-bootstrap

TLDR; How to collapse a <div> of another component in a *ngFor?

So i had a piece of code of a <table> with an *ngFor for the <tr>s and each of those rows owns a collapsible <div> connected by the index of the row.

It was all in one HTML file, both the <tr>s and the matching collapsible <div>s, collapsing and working as expected.

I wanted to organize my code and separate to components so i have created another Component for the collapsible <div> as the TransactionRowDetailsComponent with two @Inputs – the details to be displayed and the index to connect between the row and this collapsible <div>

Well, it doesn't work and i have no idea why, it does not collapse the div on clicking the row.

Debugging the creation of these TransactionRowDetailsComponent i could notice they get the details and the index correctly.

Any idea how to make it work with separate Components?

Thanks in advance!

Code Section:

Previous collapsing within one HTML:

<table class="table table-hover">
    <template let-transaction ngFor [ngForOf]="accountTransactions" let-i="index">
        <tr data-toggle="collapse" [attr.data-target]="'#'+i">
            <td>{{transaction.time}}</td>
            <td>{{transaction.description}}</td>
            <td>{{transaction.amount}}</td>
            <td>{{transaction.currency}}</td>
        </tr>
        <div class="container collapse" [attr.id]="i">
            <!-- some collapsible content -->
        </div>
    </template>
</table>

Current not collapsing separated components:

<table *ngIf="accountTransactions" class="table table-hover">
    <template let-transaction ngFor [ngForOf]="accountTransactions" let-i="index">
        <tr data-toggle="collapse" [attr.data-target]="'#'+i">
            <td>{{transaction.time}}</td>
            <td>{{transaction.description}}</td>
            <td>{{transaction.amount}}</td>
            <td>{{transaction.currency}}</td>
        </tr>
        <transaction-row-details [transaction]="transaction" [index]="i"></transaction-row-details>
    </template>
</table>

The separated TransactionRowDetailsComponent

@Component({
    selector: 'transaction-row-details',
    templateUrl: './TransactionRowDetails.html',
})
export class TransactionRowDetailsComponent {
    @Input() transaction: Transaction = new Transaction();
    @Input() index: number;

    constructor() {}
}

TransactionRowDetails.html

<div class="container collapse" [attr.id]="i">
    <!-- some collapsible content -->
</div>

Best Answer

I think problem is with i variable. It should be index(as you have index as an input variable) instead.

<div class="container collapse" [attr.id]="index">  //<----changed i to index
    Collapse me !
</div>

Working Demo : https://plnkr.co/edit/eCRqpEzvMicKpiXdD1gp?p=preview