You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:06:08