简体   繁体   English

如何通过服务在另一个组件中注入/渲染 angular 组件

[英]How to inject/render an angular component inside an another component via service

I have few common components (say C1, C2, C3) and this could be rendered in any of my screens (say S1,S2 and S3).我有几个通用组件(比如 C1、C2、C3),这可以在我的任何屏幕中呈现(比如 S1、S2 和 S3)。 In each screen, I have a placeholder( <div id="common-component-placeholder"></div> ) for common component.在每个屏幕中,我都有一个用于公共组件的占位符( <div id="common-component-placeholder"></div> )。

Now, I have a service that will run everytime a NavigationEnds and will do a simple business logic(let say it returns C1) that will tell what component to be loaded in a screen.现在,我有一个服务,它将在每次 NavigationEnds 时运行,并将执行一个简单的业务逻辑(假设它返回 C1),它将告诉屏幕中要加载的组件。

What I need to know is, how to inject the C1 into S1 via a service我需要知道的是,如何通过服务将 C1 注入 S1

You'll want to take a look at the ComponentFactoryResolver .你会想看看ComponentFactoryResolver The full (official) guide is at the angular.io - I think it describes everything very well so I will not copy paste all the information.完整的(官方)指南位于angular.io - 我认为它很好地描述了所有内容,因此我不会复制粘贴所有信息。

Basically, you'll have to inject your common service into the S1, S2 and S3.基本上,您必须将公共服务注入 S1、S2 和 S3。 That service will have a method that will accept a viewContainerRef , and will the generate the component (C1, C2, C3 based on your business logic) using the factory into that viewContainerRef .该服务将有一个接受viewContainerRef的方法,并将使用工厂生成组件(C1、C2、C3 基于您的业务逻辑)到该viewContainerRef中。

One thing to have in mind - when using factory you'll want to remember that unless you explicitly call destroy() method (or use clear() on it's parent 'viewContainerRef' if I remember correctly, but better check it yourself) it will not call OnDestroy lifecycle hook.需要记住的一件事 - 使用工厂时,您需要记住,除非您明确调用destroy()方法(或者如果我没记错的话,在它的父 'viewContainerRef' 上使用clear() ,但最好自己检查)它会不调用 OnDestroy 生命周期钩子。 This is by design, so you'll have to take care of that (since your C1, C2 and C3 might have some logic that needs clearing when they are destroyed).这是设计使然,因此您必须注意这一点(因为您的 C1、C2 和 C3 可能有一些逻辑需要在它们被销毁时清除)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM