Angular 2 включают html-шаблоны

в angular 2 Мне нужно создать большой html-шаблон с избыточными частями. Поэтому я хочу создать несколько html-шаблонов и объединить их, включив их в основной html файл (например, ng-include в угловом1)

Но как включить субшаммы в основной шаблон?

Пример:

<!-- 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>

Ответы

Ответ 1

Вы можете создавать такие компоненты, как sub1 sub2 и т.д. На этих дочерних компонентах эти HTML файлы добавляют в качестве шаблона.

В главном html вызовите селектора компонентов соответственно. Он будет работать

Ответ 2

Позвольте мне прежде всего сказать, что ng-include от Angular1.x не поддерживается Angular2, поэтому очевидно $Compile нет в Angular2. Итак, вы можете продолжить CRF-ComponentFactoryResolver, как показано здесь, чтобы динамически добавлять HTML-код с контекстом angular.

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


Если ваш фрагмент HTML имеет контекст angular, вы должны использовать CFR-ComponentFactoryResolver.

Как и в sub1.html, у вас есть button, вы можете нажать его и запустить его событие click. Это может быть достигнуто с помощью CFR, как показано ниже,

Вы можете сделать много с CRF. Это, наверное, самый простой пример.

@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);
    }
  }
}