手记

Angular2 动态渲染组件

最近在做Angular2 的预研工作,需要动态添加组件,并渲染出组件显示效果。查阅了一此资料,分享如下:
http://stackoverflow.com/questions/34784778/equivalent-of-compile-in-angular-2

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

http://www.talkinghightech.com/en/dynamically-rendering-components-angular2/

http://www.tuicool.com/articles/JfiyUrJ

2人推荐
随时随地看视频
慕课网APP

热门评论

DynamicComponentLoader   这个AP现在好像被移除了

查看全部评论