Angular2-按需渲染组件并附加到主体中
我正在尝试创建一个插件,它以一个组件作为参数,并在body标签的末尾呈现其内容。就像使用jQuery的插件一样Angular2-按需渲染组件并附加到主体中,angular,dependency-injection,Angular,Dependency Injection,我正在尝试创建一个插件,它以一个组件作为参数,并在body标签的末尾呈现其内容。就像使用jQuery的插件一样 @Component({ selector: 'some-selector', template: 'This is FirstComponent' }) class FirstComponent{} @Component({ selector: 'app', template: 'The root component' }) class AppCom
@Component({
selector: 'some-selector',
template: 'This is FirstComponent'
})
class FirstComponent{}
@Component({
selector: 'app',
template: 'The root component'
})
class AppComponent{
// ImaginaryModalOpener is what i want to achieve.
// a standalone function that can take a component and render it in dom
// at the bottom of the body tag
ImaginaryModalOpener(FirstComponent);
}
我已经看到了很多关于呈现动态组件的stackoverflow问题,但是他们在根组件中使用了指令或HTML标记。
在我的例子中,根模板没有ImaginaryModalOpener的指令或组件
如果我遗漏了什么,请指出。从
AppComponent
获取ViewContainerRef
并向该ViewContainerRef
添加一个组件,如中所示
添加的组件将作为同级添加到
AppComponent
。如果AppComponent
是
的子组件,则动态添加的组件也将是
的子组件。您可以根据需要从renderFactory2
创建一个Renderer2
,并使用该组件添加到document.body
我需要为第三方跟踪API添加一个iframe
,该API需要我在用户购买时在页面上放置一个iframe
。因此,这个示例在逻辑上属于一个服务,而不是一个组件——碰巧实现会导致添加一个DOM元素
注入这些(即使providerIn:'root'
):
然后,要创建iFrame,请执行以下操作:
createIFrame(url: string)
{
const iframe: HTMLIFrameElement = document.createElement('iframe');
iframe.src = url;
iframe.width = '100';
iframe.height = '100';
iframe.frameBorder = '1';
const renderer = this.rendererFactory.createRenderer(null, null);
renderer.appendChild(this.document.body, iframe);
}
就这样。不要乱搞
AppComponent
或ViewReference
等-这基本上只是角度形式的纯Javascript。应该给你一个解决方案,它不是用户视图容器引用,而是使用直接DOM节点将组件插入Thank!,我终于想出了这个代码,将组件附加到主体上。干杯让factory=this.resolver.resolveComponentFactory(options.component);让newNode=document.createElement('div');document.body.appendChild(newNode);const ref:any=factory.create(this.injector,[],newNode);此.app.attachView(参考hostView);
createIFrame(url: string)
{
const iframe: HTMLIFrameElement = document.createElement('iframe');
iframe.src = url;
iframe.width = '100';
iframe.height = '100';
iframe.frameBorder = '1';
const renderer = this.rendererFactory.createRenderer(null, null);
renderer.appendChild(this.document.body, iframe);
}