Is there any alternate way in angular to achieve what ng-include does in angularjs?
The closest to ng-include is ngTemplateOutlet directive. You need to pass a TemplateRef to it and optional context. Something like that:
@Component({
selector: 'child',
template: `
<div>
here is child template that includes myTemplate
<ng-container [ngTemplateOutlet]="myTemplate"></ng-container>
</div>`
})
export class ChildComponent {
@Input() myTemplate: TemplateRef<any>;
}
@Component({
selector: 'app-root',
template: `
<p>Parent</p>
<child [myTemplate]="myTemplate"></child>
<ng-template #myTemplate>hi julia template!</ng-template>
`
})
export class AppComponent {
@ViewChild('myTemplate', {read: TemplateRef}) myTemplate: TemplateRef<any>;
}
Thinking from angular2+ way it's better to declare the child template as component:
@Component({
selector: 'app-child',
template: `
<ng-container>
here is child template that includes myTemplate
</ng-container>`
})
export class ChildComponent {
}
@Component({
selector: 'app-root',
template: `
<p>Parent</p>
<app-child ></app-child>
`
})
export class AppComponent {
}
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