Angular13使用Directive调用viewContainerRef.createComponent如何向动态组件传参
Angular 13 动态创建组件传参实现方案
核心原理是ViewContainerRef.createComponent()执行后会返回动态组件的实例引用ComponentRef,通过该引用可直接为动态组件的@Input属性赋值,实现业务参数传递,具体实现步骤如下:
1. 修改LoaderDirective指令
新增参数接收输入属性,创建组件完成后将参数赋值给动态组件实例:
import { Directive, Input, ViewContainerRef, Type, OnInit } from '@angular/core'; @Directive({ selector: '[appLoader]' }) export class LoaderDirective implements OnInit { @Input() appLoader!: Type<any>; // 新增输入属性,接收外部传入的业务参数 @Input() appLoaderParams?: Record<string, any>; constructor(private viewContainerRef: ViewContainerRef) {} ngOnInit(): void { const componentRef = this.viewContainerRef.createComponent(this.appLoader); // 为动态组件赋值业务参数 if (this.appLoaderParams) { componentRef.instance.businessData = this.appLoaderParams; // 手动触发变更检测,确保参数立即生效 componentRef.changeDetectorRef.detectChanges(); } } }
2. 为动态组件添加参数接收属性
在你的MyComponent中添加@Input属性用于接收业务参数:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-my-component', template: `<!-- 组件内部可直接使用businessData的字段 --> <p>当前登录用户ID:{{businessData?.userId}}</p> <p>业务场景:{{businessData?.scene}}</p>` }) export class MyComponent { // 接收父组件传入的业务参数,可根据实际业务定义具体类型 @Input() businessData!: { userId: number; scene: string; // 其他自定义业务字段 }; }
3. 修改父组件传递参数
app.component.ts 新增业务参数定义:
component = MyComponent; // 你的自定义业务参数对象 businessInfo = { userId: 12345, scene: '订单详情页', // 其他需要传递的业务信息 }
app.component.html 新增参数绑定:
<div [appLoader]="component" [appLoaderParams]="businessInfo"></div>
可选扩展
如果需要支持动态更新参数,可将指令的appLoaderParams改为set监听器,参数变化时自动更新动态组件的属性值即可。
内容的提问来源于stack exchange,提问作者deszok
相关产品推荐
相关产品推荐

