In Angular 1.x, we could insert HTML in real-time by using the HTML tag ng-bind-html
, combined with the JavaScript call $sce.trustAsHTML()
. This go
In Angular2 you should use DynamicComponentLoader to insert some "compiled content" on the page. So for example if you want to compile next html:
Common HTML tag
Some angular2 component
then you need to create component with this html as a template (let's call it CompiledComponent
) and use DynamicComponentLoader
to insert this component on the page.
@Component({
selector: 'compiled-component'
})
@View({
directives: [Angular2Component],
template: `
Common HTML tag
Angular 2 component
`
})
class CompiledComponent {
}
@Component({
selector: 'app'
})
@View({
template: `
Before container
After conainer
`
})
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
Check out this plunker
UPD You can create component dynamically right before the loader.loadIntoLocation()
call:
// ... annotations
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
// template generation
const generatedTemplate = `${Math.random()}`;
@Component({ selector: 'compiled-component' })
@View({ template: generatedTemplate })
class CompiledComponent {};
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
I personally don't like it, it's look like a dirty hack to me. But here is the plunker
PS Beware that at this moment angular2 is under active development. So situation can be changed at any time.