Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the alternative for "ng-include" in angular2?

Tags:

angular

Is there any alternate way in angular to achieve what ng-include does in angularjs?

like image 544
sumit dhingra Avatar asked Apr 16 '17 18:04

sumit dhingra


2 Answers

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>;
}
  1. Parent component querys the template and passes it to the child component
  2. Child component uses ngTemplateOutlet directive to create view and render it.
like image 52
Julia Passynkova Avatar answered Oct 21 '22 12:10

Julia Passynkova


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 {
}
like image 30
Bogdan Avatar answered Oct 21 '22 11:10

Bogdan