angular - Angular - 使用服务将组件插入到另一个组件中
问题描述
所以我希望能够将一个组件传递给一个服务,然后服务将插入这个组件并将数据传递给另一个,例如:
app.component:需要在side上显示信息,调用aside.show(Component, data).side.service:接收组件和数据并插入到aside.generic中。
只需调用aside.service 并传递一些参数来显示aside,如果您使用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,它做同样的事情:
以下是链接:
https://stackblitz.com/edit/dynamic-component-j2m3c1?file=app%2Fservice.ts
这应该让您对如何在您的特定情况下实施它有一个公平的想法
推荐阅读
- python - 如何使用 Python 块读取文件
- python - python编程使用codeskulptor:使用simplegui的简单计算器
- javascript - 为什么 AJAX 函数不会立即从数据库中获取数据?
- c++ - =声明与定义中的默认值
- json - Ionic 3 和 JSON:在网格中添加名称的麻烦
- reactjs - Redux 使用问题@connect
- python - 如何将json数据帧转换为其他数据帧
- node.js - 如何快速为全球客户提供 node.js 服务?
- vba - 如何通过 Excel VBA 更新 Sharepoint 列表项
- javascript - 使用 JavaScript 对逗号分隔的字符串数组进行排序