Equivalent of $compile in Angular 2

后端 未结 9 840
名媛妹妹
名媛妹妹 2020-11-21 06:50

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 dynamic

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 07:03

    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) {
      @Component({ 
        selector: 'fake', 
        template , directives
      })
      class FakeComponent {};
      return FakeComponent;
    }
    
    @Component({
      selector: 'hello',
      template: '

    Hello, Angular!

    ' }) class Hello {} @Component({ selector: 'my-app', template: '
    ', }) export class App implements OnInit { constructor( private loader: DynamicComponentLoader, private elementRef: ElementRef, ) {} ngOnInit() {} { const someDynamicHtml = `

    ${Date.now()}

    `; this.loader.loadIntoLocation( compileToComponent(someDynamicHtml, [Hello]) this.elementRef, 'container' ); } }

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

提交回复
热议问题