[英]angular 2 include html templates
in angular 2 I need to create a large html-template with redundant parts. 在角度2我需要创建一个带有冗余部分的大型html模板。 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)
因此,我想创建多个html模板,并将它们包含在主html文件中(如angular1中的ng-include)
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>
You can create components like sub1 sub2 etc. And On those child components add these html files as template . 您可以创建sub1 sub2等组件。在这些子组件上添加这些html文件作为模板。
On main html call the component selectors respectively. 在主html上分别调用组件选择器。 It will work
它会工作
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
. 首先,让我所有的告诉你
ng-include
从Angular1.x
不Angular2支撑明显$Compile
没有出现在Angular2
。 So, you can go ahead with CRF-ComponentFactoryResolver
as shown here to add HTML dynamically with angular context. 因此,您可以继续使用
CRF-ComponentFactoryResolver
,如此处所示,使用角度上下文动态添加HTML。
DEMO--(CFR) : https://plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p=preview 演示 - (CFR) : https : //plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p = preview
If your HTML piece has angular context, you should use CFR-ComponentFactoryResolver
. 如果您的HTML片段具有角度上下文,则应使用
CFR-ComponentFactoryResolver
。
As in sub1.html
, you have button
, you might want to click it and fire its click event. 与
sub1.html
,您有button
,您可能想要单击它并触发其click事件。 This can be achieved with CFR
as shown below, 这可以通过
CFR
实现,如下所示,
You can do lot with CRF
. 您可以使用
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.