首页 > 解决方案 > Angular - 使用服务将组件插入到另一个组件中

问题描述

所以我希望能够将一个组件传递给一个服务,然后服务将插入这个组件并将数据传递给另一个,例如:

app.component:需要在side上显示信息,调用aside.show(Component, data).side.service:接收组件和数据并插入到aside.generic中。

只需调用aside.service 并传递一些参数来显示aside,如果您使用ngx-bootstrap,我希望它能够按照模式在那里的工作方式工作。

标签: angularangular-components

解决方案


我想你想添加动态组件:

因此,要使用服务添加动态组件,您可以这样做:

在你的app.component.ts

import { Component, ViewContainerRef, OnInit } from '@angular/core';
import { Service } from './service'
import { DynamicComponent } from './dynamic.component'
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
   constructor(public service: Service, public viewContainerRef: ViewContainerRef) {
  }
  add(){
    this.service.setRootViewContainerRef(this.viewContainerRef);
    this.service.addDynamicComponent()
  }
}

在你的service.ts

import {
  ComponentFactoryResolver,
  Injectable,
  Inject,
  ReflectiveInjector
} from '@angular/core'

import { DynamicComponent } from './dynamic.component'

@Injectable()
export class Service {
  rootViewContainer:any;

  constructor(private factoryResolver: ComponentFactoryResolver) { }

  public setRootViewContainerRef(viewContainerRef) {
    this.rootViewContainer = viewContainerRef
  }

  public addDynamicComponent() {
    const factory = this.factoryResolver.resolveComponentFactory(DynamicComponent)
    const component = factory.create(this.rootViewContainer.parentInjector)

    this.rootViewContainer.insert(component.hostView)
  }

}

我创建了一个工作的 stackblitz url,它做同样的事情:

以下是链接:

https://stackblitz.com/edit/dynamic-component-j2m3c1?file=app%2Fservice.ts

这应该让您对如何在您的特定情况下实施它有一个公平的想法


推荐阅读