Angular - 使用服务将组件插入另一个组件

Angular - Use a service to insert a component intro another one

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

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

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

我想你想添加动态组件:

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

在你的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,它的作用相同:

下面是link:

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

这应该让您对如何在您的具体情况下实施它有一个清晰的认识