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)...
ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.
ViewChild is used to select an element from component's template while ContentChild is used to select projected content.
The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.
The ContentChild & ContentChildren are decorators, which we use to Query and get the reference to the Projected Content in the DOM. Projected content is the content that this component receives from a parent component. The ContentChild & ContentChildren is very similar to the ViewChild & ViewChildren.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With