簡體   English   中英

angular 2包括html模板

[英]angular 2 include html templates

在角度2我需要創建一個帶有冗余部分的大型html模板。 因此,我想創建多個html模板,並將它們包含在主html文件中(如angular1中的ng-include)

但是如何在主模板中包含子模板?

例:

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

您可以創建sub1 sub2等組件。在這些子組件上添加這些html文件作為模板。

在主html上分別調用組件選擇器。 它會工作

首先,讓我所有的告訴你ng-includeAngular1.x不Angular2支撐明顯$Compile沒有出現在Angular2 因此,您可以繼續使用CRF-ComponentFactoryResolver ,如此處所示,使用角度上下文動態添加HTML。

演示 - (CFR)https//plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p = preview


如果您的HTML片段具有角度上下文,則應使用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);
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM