20

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,482
  • 8
  • 34
  • 51

1 Answers1

40

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
  • 4,227
  • 3
  • 18
  • 19
yurzui
  • 190,482
  • 29
  • 403
  • 383
  • 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