angular2仅从字符串生成组件 [英] angular2 generate component from just a string

查看:83
本文介绍了angular2仅从字符串生成组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉您如何在Angular2/4中执行以下操作:

Please, tell how to do the following in Angular2/4 :

组件SomeComponent@Input作为字符串从以下html获取:

Component SomeComponent gets from @Input the following html as a string :

  `<am-input
    [placeholder]="'Placeholder'"
    [disabled]="true">
  </am-input>`

SomeComponent如何仅通过该字符串在其内部创建组件?

How can SomeComponent create a component inside itself from only that string ?

谢谢

推荐答案

唯一的选择是使用JIT编译器,并在获得它时对其进行编译.阅读此处是您需要了解Angular中的动态组件,特别是Creating components on the fly部分.它详细说明了该过程.要点如下:

The only option is to use JIT compiler and compile it when you get it. Read the Here is what you need to know about dynamic components in Angular, specifically Creating components on the fly part. It explains the process in details. Here is the gist:

class SomeComponent {
  @Input inputTpl;
  constructor(private _compiler: Compiler,
            private _injector: Injector,
            private _m: NgModuleRef<any>) {
  }

  ngOnChanges() {  
    const tmpCmp = Component({template: inputTpl})(class {});
    const tmpModule = NgModule({declarations: [tmpCmp]})(class {});

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
      .then((factories) => {
        const f = factories.componentFactories[0];
        const cmpRef = f.create(this._injector, [], null, this._m);
        cmpRef.instance.name = 'dynamic';
        this.vc.insert(cmpRef.hostView);
      })
    }

这篇关于angular2仅从字符串生成组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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