的$等效编译角2 [英] Equivalent of $compile in Angular 2

查看:139
本文介绍了的$等效编译角2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想手动编译包含指令的一些HTML。什么是$等值角2编译?

例如,在1角,我可以动态编译HTML片段,并追加到DOM:

 变种E = angular.element('< D​​IV&指令GT;< / DIV>');
element.append(E);
$编译(E)($范围内);


解决方案

Angular2没有任何 $编译等价的。您可以使用<一个href=\"https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html\"><$c$c>DynamicComoponentLoader与ES6类劈死动态编译code(见本普拉克):

进口{组件,DynamicComponentLoader,ElementRef}从'angular2 /核心功能compileToComponent(模板,指令){
  @零件({
    选择:'假',
    模板,指令
  })
  类FakeComponent {};
  返回FakeComponent;
}@零件({
  选择:'你好',
  模板:'&LT; H1&GT;您好,角&LT; / H1&GT;!
})
您好类{}@零件({
  选择:我的应用,
  模板:'&LT; D​​IV#集装箱&GT;&LT; / DIV&GT;,
})
出口类应用{
  构造器(装载机:DynamicComponentLoader,elementRef:ElementRef){
    常量some​​DynamicHtml =`&LT;&打招呼GT;&LT; /你好&GT;&LT; H2&GT; $ {Date.now()}&LT; / H&GT;`;    loader.loadIntoLocation(
      compileToComponent(someDynamicHtml,[你好])
      elementRef,
      '容器'
    );
  }
}

但是,直到HTML解析器是angular2核心里面才会工作。

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

解决方案

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} from 'angular2/core'

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

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

@Component({
  selector: 'my-app',
  template: '<div #container></div>',
})
export class App {
  constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
    const someDynamicHtml = `<hello></hello><h2>${Date.now()}</h2>`;

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

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

这篇关于的$等效编译角2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆