【问题标题】:Angular2 - rendering component on demand and append in bodyAngular2 - 按需渲染组件并附加在正文中
【发布时间】:2017-07-09 17:29:49
【问题描述】:

我正在尝试创建一个插件,该插件将组件作为参数并在正文标记的末尾呈现其内容。就像使用 jQuery 的插件一样。

@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 的指令或组件。

如果我遗漏了什么,请指出。

【问题讨论】:

  • this answer 应该为您提供解决方案,它不会让用户查看容器 ref,而是使用直接 DOM 节点将组件插入

标签: angular dependency-injection


【解决方案1】:

AppComponenthow to get root viewContainerRef of angular2 aplication获取ViewContainerRef

并向ViewContainerRef 添加一个组件,例如Angular 2 dynamic tabs with user-click chosen components 中所示

添加的组件将作为兄弟添加到AppComponent。如果AppComponent<body> 的子级,则动态添加的组件也将是<body> 的子级。

【讨论】:

  • 谢谢!我终于想出了这段代码,将组件附加到正文中。干杯。让工厂 = this.resolver.resolveComponentFactory(options.component);让 newNode = document.createElement('div'); document.body.appendChild(newNode); const ref: any = factory.create(this.injector, [], newNode); this.app.attachView(ref.hostView);
【解决方案2】:

您可以根据需要从RendererFactory2 创建Renderer2,并使用它添加到document.body

我需要为第三方跟踪 API 添加 iframe,当用户购买时,我需要在页面上添加 iframe。所以这个例子在逻辑上属于一个服务而不是一个组件——它的实现恰好导致添加了一个 DOM 元素。

注入这些(即使providerIn: 'root'):

 private rendererFactory: RendererFactory2,
 @Inject(DOCUMENT) private document: Document

然后创建一个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);
}

就是这样。不要乱用 AppComponentViewReference 等 - 这基本上只是 Angular 形式的纯 Javascript。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2016-02-02
    • 2016-06-09
    相关资源
    最近更新 更多