推荐答案此答案基于 stackblitz示例在此答案中提供到我问的类似问题.This answer is based on the stackblitz example provided in this answer to a similar question I asked. 第1步:创建一个指令,该指令将在您希望拥有可重用组件的任何地方使用.Step #1: Create a directive that you will use wherever you want to have your reusable component.@Directive({ selector: '[reusable-outlet]',})export class ReusableDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private reusableService: ReusableService ) { } public ngOnInit(): void { this.reusableService.attach(this.viewContainerRef); }} 步骤2 创建将负责以下服务的服务:Step #2 Create the service that will be in charge of:动态创建将被重用的组件将该组件附加和分离到步骤〜1中创建的指令的视图容器中.注意:知道何时分离组件是基于路由器事件的,但是,如果您需要更改组件的位置而无需进行导航更改,则应该可以基于消息来代替它.Note: Knowing when to detach the component is based on router events, but it should be possible to base it on messages instead, if you need to change where your component is without having navigation changes.@Injectable()export class ReusableService { private componentRef: ComponentRef<ReusableComponent>; private currentViewContainerRef: ViewContainerRef; constructor( private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector, private router: Router ) { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ReusableComponent); this.componentRef = componentFactory.create(injector); this.router.events.subscribe(event => { if (event instanceof NavigationStart && this.currentViewContainerRef) { this.detach(this.currentViewContainerRef); } }); } public attach(viewContainerRef: ViewContainerRef) { this.currentViewContainerRef = viewContainerRef; viewContainerRef.insert(this.componentRef.hostView); } public detach(viewContainerRef: ViewContainerRef) { viewContainerRef.detach(viewContainerRef.indexOf(this.componentRef.hostView)); }} 这篇关于是否可以在多个位置显示单个角度分量实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-13 19:05