ZanattMan
ZanattMan

Reputation: 736

ContentChildren for all children

I'm creating a list of components from Back End data. I'm creating a ContentChild object to get the reference of them but there is no data in it. I've also tried with ViewChild but I only get the first.

There are different solutions in there but none of them is working. For this reason, I think this happens because the children components are created after the class is created (I may be wrong).

This is what I've done so far:

table.component.ts

export class tableComponent {
  @ContentChildren('relation') relationElements: QueryList<RelationElement>;
}
  colapseColumn(){
    this.table.resetChildElements();
    console.log(this.relationElements);

  }

table.component.html

<ng-container *ngFor="let entity of table.tableEntity">
    <tr class="listTable--bodyRow" >
        <td class="listTable--bodyElement"
            *ngFor="let element of entity.printableElements">
            <container-relation
                #relation
                [element]="element"
                (collapseColumn)="colapseColumn();">
            </container-relation>
       </td
   </tr>
</ng-container> 

UPDATE

I've tried with ViewChildren:

@ViewChildren('relation') relationElements: QueryList<any[]>;

When printing relationElements I'm getting the following result:

QueryList {_dirty: false, _results: Array(0), _emitter: EventEmitter

The expected result should allow me to do something like:

this.relationElements.map(re => re.extended = false);

Upvotes: 1

Views: 2610

Answers (1)

n00dl3
n00dl3

Reputation: 21564

There is an Observable changes property on QueryList class, you can subscribe to it to get notified when a component is added or removed. You should also use @ViewChildren() instead of @ContentChildren() as there is apparently no ng-content in your template.

@ViewChildren('relation')
relationElements: QueryList<RelationElement>;

ngAfterViewInit(){
  this.relationElements.changes
    .startWith(this.relationElements).subscribe(()=>{
      console.log(this.relationElements);
      // do stuff when list updates
    });
}

Working plnkr

Upvotes: 2

Related Questions