Hãy để tôi nói với bạn đầu tiên của tất cả những gì ng-include
từ Angular1.x
không phải là s được hỗ trợ bởi Angular2 nên rõ ràng là $Compile
không có trong Angular2
. Vì vậy, bạn có thể tiếp tục với CRF-ComponentFactoryResolver
như được hiển thị ở đây để thêm HTML động với bối cảnh góc cạnh.
DEMO - (CFR): https://plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p=preview
Nếu mảnh HTML của bạn có bối cảnh góc cạnh, bạn nên sử dụng CFR-ComponentFactoryResolver
.
Như trong sub1.html
, bạn có button
, bạn có thể muốn nhấp vào nó và bắn sự kiện click của nó. Điều này có thể đạt được với CFR
như hình dưới đây,
Bạn có thể làm rất nhiều với CRF
. Đây có lẽ là ví dụ dễ nhất.
@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);
}
}
}
không có bất kỳ ngữ cảnh góc nào trong đó? hoặc chỉ 'div' và' văn bản tĩnh'? – micronyks
chắc chắn là vậy. Tôi có nhiều {{}} và * ngIf, ngFor, ... nhưng làm cách nào để đưa các mẫu khác vào mẫu chính? –
Điều này có hữu ích không? http://stackoverflow.com/questions/12863663/complex-nesting-of-partials-and-templates – natel