Julian
Julian

Reputation: 763

How to dynamically add a component in a table tr forloop in Angular 2

I have a table which loops through each row. When a use clicks a link in the row, I can create a child row below. The problem is, this child row, I would like it to be a component so I can pass data to it. Is this possible?

My code is below account.component.html

 <tr *ngFor="let account of accounts">
                        <td (click) ="showChildRow($event, account)" >{{ account.name }}</td>
                        <td>{{ account.id }}</td>
                    </tr>

account.component.ts

showChildRow(event:any, account: Object){
  var tableId = $(event.target).closest('table')[0].id;
  var table = $('#' + tableId).DataTable();
  var tr = $(event.target).closest('tr');
  var row = table.row( tr );

  if ( row.child.isShown() ) {

      $('div.slider', row.child()).slideUp( function () {
        row.child.hide();
        tr.removeClass('shown');
      } );
  }
  else {

      this.accountService.getAccountInfo(account.id)
                      .subscribe(
                        data => this.format(data, row, tr),
                        error =>  this.errorMessage = <any>error
                      )

  }
}


format ( data, row, tr ) {

  var childRow = '<div class="slider col-xs-12">'+
                    '<child-component [data] ="data"></child-component>' //HOW TO DYNAMICALLY ADD COMPONENT?
                 '</div>';

  row.child(childRow).show();
  tr.addClass('shown');
  $('div.slider', row.child()).slideDown();
}

Upvotes: 1

Views: 2013

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

You need to use a attribute selector, because <table> doesn't allow arbitrary tags

<table>
  <tr myAccount *ngFor="let account of accounts>
</table>
@Component({
  selector: '[myAccount]',
  ...
})

Upvotes: 2

Related Questions