加载在angular2final中动态创建的组件
Load dynamic component created on the fly in angular2 final
以前使用DynamicComponentLoader
时,我可以这样写:
import {Directive, Component, ViewContainerRef, DynamicComponentLoader} from '@angular/core';
@Directive({
selector: '[some-directive]'
})
export class SomeDirective {
costructor(dcl: DynamicComponentLoader, viewContainerRef: ViewContainerRef) {
// fetch template from the server
fetch(...).then((template) => {
@Component({
selector: 'div[some-relatively-unique-attribute-name]',
template: template
})
class AdHocComponent {}
dcl.loadNextToLocation(AdHocComponent, viewContainerRef).then(() => {
console.log('success');
});
});
}
}
现在使用angular2 final和NgModules
,我看到这样的例子:http://plnkr.co/edit/P0spNzu8JbQad2aKACsX?p=info
(此处讨论https://github.com/angular/angular/issues/10735)
动态加载HelloComponent
,但它需要在创建根NgModule
时预先声明HelloComponent。
我如何加载一个特别创建的组件到我的视图?
我发现这个:http://plnkr.co/edit/wh4VJG?p=preview但是,要完成这样一个简单的任务,代码量实在是太大了。
这可能就是你要找的:
export class App {
@ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
constructor(private compiler: Compiler) {}
addItem () {
@NgModule({declarations: [HelloComponent]})
class DynamicModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
.then(({moduleFactory, componentFactories}) => {
const compFactory = componentFactories
.find(x => x.componentType === HelloComponent);
const cmpRef = this.viewContainerRef.createComponent(compFactory, 0);
});
}
}
参见live Plunker
相关问题:
- Angular2 RC6 -从模块动态加载组件
相关文章:
- 如何创建带有插槽的vue js组件预加载程序
- 如何在cycle js中从JSON数组创建组件
- 使用数据数组创建多个类似组件
- 使用knockoutjs组件创建对话框
- 如何使用浏览器中用酶创建的组件反应例如摩卡
- 如何创建独立于数组更新的组件列表
- 如何创建一个组件,我可以设置在 Angular 2 中的属性中获取 URL 数据
- 使用 XPCOM 和 JavaScript 为 Firefox 创建附加组件
- ExtJS 4.1.它们是创建侧边栏菜单的最佳组件(如左面板中的Worpress)
- 如何使用onClick处理程序在React组件中创建链接
- 在React Native中批量创建组件
- React Native:创建组件错误
- 如何使用 React.createElement 基于 prop 或变量动态创建组件
- 如何在Reactjs中创建组件实例
- 在React.js中创建组件是"React.createClass"仍然可用
- Qt不会创建组件,也不会返回错误
- 是否可以在ExtJS中从远程json对象创建组件?
- 如何在React native中创建组件映射
- Ember:动态创建组件动作don'不要开火
- 如何用样板创建组件层次结构