I want to manually compile some HTML containing directives. What is the equivalent of $compile
in Angular 2?
For example, in Angular 1, I could dynamically compile a fragment of HTML and append it to the DOM:
var e = angular.element('<div directive></div>');
element.append(e);
$compile(e)($scope);
Note: As @BennyBottema mentions in a comment, DynamicComponentLoader is now deprecated, hence so is this answer.
Angular2 doesn't have any $compile equivalent. You can use
DynamicComoponentLoader
and hack with ES6 classes to compile your code dynamically (see this plunk):But it will work only until html parser is inside angular2 core.
this npm package made it easier for me: https://www.npmjs.com/package/ngx-dynamic-template
usage:
Angular 2.3.0 (2016-12-07)
To get all the details check:
To see that in action:
The principals:
1) Create Template
2) Create Component
3) Create Module
4) Compile Module
5) Create (and cache) ComponentFactory
6) use Target to create an Instance of it
A quick overview how to create a Component
A way how to inject component into NgModule
A code snippet how to create a
ComponentFactory
(and cache it)A code snippet how to use the above result
The full description with all the details read here, or observe working example
.
.
In order to dinamically create an instance of a component and attach it to your DOM you can use the following script and should work in Angular RC:
html template:
Loader component
Angular TypeScript/ES6 (Angular 2+)
Works with AOT + JIT at once together.
I created how to use it here: https://github.com/patrikx3/angular-compile
Component: Should have a context and some html data...
Html:
If you want to inject html code use directive
If you want to load whole component in some place, use DynamicComponentLoader:
https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html