21

in angular 2 I need to create a large html-template with redundant parts. Therefore I want to create multiple html-templates and put them together by including them in the main html-file (like ng-include in angular1)

But how can I include sub-templates in the main-template?

example:

<!-- test.html -->

<div>
    this is my Sub-Item
    <!-- include sub1.html here-->
</div>
<div>
    this is second Sub-Item
    <!-- include sub2.html here-->
</div>

-

<!-- sub1.html -->
<div>
    <button>I'am sub1</button>
</div>

-

<!-- sub2.html -->
<div>
    <div>I'am sub2</div>
</div>
Tobias Koller
  • 2,116
  • 4
  • 26
  • 46

2 Answers2

16

You can create components like sub1 sub2 etc. And On those child components add these html files as template .

On main html call the component selectors respectively. It will work

Aswin KV
  • 1,710
  • 2
  • 12
  • 23
2

Let me tell you first of all that ng-include from Angular1.x is not supported by Angular2 so obviously $Compile is not present in Angular2. So, you can go ahead with CRF-ComponentFactoryResolver as shown here to add HTML dynamically with angular context.

DEMO--(CFR) : https://plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p=preview


If your HTML piece has angular context, you should use CFR-ComponentFactoryResolver.

As in sub1.html, you have button, you might want to click it and fire its click event. This can be achieved with CFR as shown below,

You can do lot with CRF. This is probably the easiest example.

@Component({
  selector: 'my-app',
  template: `

     <button (click)="addComponents()">Add HTML (dynamically using CRF)</button>

     <h1>Angular2 AppComponent</h1>
     <hr>

     <div>
     <h5>sub1.html goes here</h5>
      <div class="container">
        <template #subContainer1></template>
      </div>
     </div>

     <hr>
     <h5>sub2.html goes here</h5>
     <div class="container">
        <template #subContainer2></template>
     </div>
  `,

})
export class App {
    name:string;
    @ViewChild('subContainer1', {read: ViewContainerRef}) subContainer1: ViewContainerRef;
    @ViewChild('subContainer2', {read: ViewContainerRef}) subContainer2: ViewContainerRef;
    constructor(
      private compFactoryResolver: ComponentFactoryResolver
      ) {
      this.name = 'Angular2'
    }

    addComponents() {

      let compFactory: ComponentFactory;

      compFactory = this.compFactoryResolver.resolveComponentFactory(Part1Component);
      this.subContainer1.createComponent(compFactory);


      compFactory = this.compFactoryResolver.resolveComponentFactory(Part2Component);
      this.subContainer2.createComponent(compFactory);
    }
  }
}
micronyks
  • 54,797
  • 15
  • 112
  • 146