加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2 – 在Angular 2中等价于$compile

发布时间:2020-12-17 08:56:24 所属栏目:安全 来源:网络整理
导读:我想手动编译一些包含指令的HTML。在Angular 2中相当于$ compile是什么? 例如,在Angular 1中,我可以动态编译一个HTML的片段并将其附加到DOM: var e = angular.element('div directive/div');element.append(e);$compile(e)($scope); 注意:由于@BennyBot
我想手动编译一些包含指令的HTML。在Angular 2中相当于$ compile是什么?

例如,在Angular 1中,我可以动态编译一个HTML的片段并将其附加到DOM:

var e = angular.element('<div directive></div>');
element.append(e);
$compile(e)($scope);
注意:由于@BennyBottema在注释中提及,DynamicComponentLoader现在已被弃用,因此这个答案也是如此。

Angular2没有任何$compile等效。你可以使用DynamicComoponentLoader和hack with ES6类来动态编译你的代码(见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: '<h1>Hello,Angular!</h1>'
})
class Hello {}

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

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

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

但它只会工作,直到html解析器里面的angular2核心。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读