25

Is it possible to use templates in combination with ng-content like described here:

app component:

<table-column>
  <template #template let-item="item">
    <input type="text" [(ngModel)]="item.foo" />
  </template>
</table-column>

table-column component:

@Component({
  selector: 'table-column',
  template: '<ng-content></ng-content>'
})
export class TableColumnComponent implements OnInit {
  @ViewChild('template') template;  

  ngOnInit() {
    console.log(this.template); // undefined
    // create column object with template and different metadata...
  });      
}

Plunker?

The problem I get undefined using different life cycle hooks (ngOnInit, ngAfterViewInit)...

Ievgen Martynov
  • 7,870
  • 8
  • 36
  • 52

1 Answers1

46

If you want to search within Light DOM then you need to use @ContentChild and wait until ngAfterContentInit hook

@ContentChild('template') template;  

ngAfterContentInit() {
  console.log(this.template);
}

See also

Joel Duckworth
  • 5,455
  • 3
  • 20
  • 21
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • This must be one of the most amazing answers ever. It's incredibly short, yet contains absolutely everything necessary to access child-elements the Angular way (without using e.g. `document.getElementsByClass(...)`). Thank you so much! – Igor Jun 23 '20 at 23:26