Я думаю, вы хотите добавить динамический компонент:
Таким образом, чтобы добавить динамический компонент с помощью сервиса, вы можете сделать так:
В вашем 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)
}
}
Я создал рабочий URL-адрес stackblitz, который делает то же самое:
Ниже приведена ссылка:
https://stackblitz.com/edit/dynamic-component-j2m3c1?file=app%2Fservice.ts
Это должно дать вам четкое представление о том, как реализовать его в вашем конкретном случае