pixelbits pixelbits - 6 months ago 100
TypeScript Question

Equivalent of $compile in Angular 2

I want to manually compile some HTML containing directives. What is the equivalent of

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>');


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):

import {Component, DynamicComponentLoader, ElementRef, OnInit} from 'angular2/core'

function compileToComponent(template, directives) {
    selector: 'fake', 
    template , directives
  class FakeComponent {};
  return FakeComponent;

  selector: 'hello',
  template: '<h1>Hello, Angular!</h1>'
class Hello {}

  selector: 'my-app',
  template: '<div #container></div>',
export class App implements OnInit {
    private loader: DynamicComponentLoader, 
    private elementRef: ElementRef,
  ) {}

  ngOnInit() {} {
    const someDynamicHtml = `<hello></hello><h2>${Date.now()}</h2>`;

      compileToComponent(someDynamicHtml, [Hello])

But it will work only until html parser is inside angular2 core.