首页 > 解决方案 > 将值注入Angular中的动态组件

问题描述

我正在开发一个允许用户动态输入规则的组件,这些规则可以是不同的类型,并且取决于规则类型,将捕获不同的值。

我已经创建了动态组件,我的问题是将初始值传递给动态创建的组件。

这些值因规则而异,因此我尝试在注入器中使用 useValue 但如果我添加参数以接受构造函数中的值,则它无法解析参数。

我的组件注射器:

getInjector(rule) {
  let inject = this.injectors[rule.name];
  if (!inject) {
    inject = Injector.create([{ provide: 'initialValues', useValue: rule.values }], this.inj);
    this.injectors[rule.name] = inject;
  }

  return inject;
}

我想要类似的东西:

export class MandatoryRuleComponent implements OnInit {
  values: any={};
  constructor(initialValues:any) { this.values = initialValues }

  ngOnInit() {
  if(!this.values.threshold){
    this.values.threshold = 9;
  }
 }
}

完整的代码可以在Stackblitz上找到

标签: angulardependency-injection

解决方案


您需要在动态组件中获取传递值。见官方例子

因此,在您的情况下,请执行以下操作:

import { Component, OnInit, Injector } from '@angular/core';

@Component({
  selector: 'app-deprecated-rule',
  templateUrl: './deprecated-rule.component.html',
  styleUrls: ['./deprecated-rule.component.css']
})
export class DeprecatedRuleComponent implements OnInit {

  values: any = {};

  constructor(private injector: Injector) { }

  ngOnInit() {
    // get provided data
    this.values = this.injector.get('initialValues');

    if (!this.values.adjustment) {
      this.values.adjustment = 999;
    }
  }
}

另请注意

  • 字符串令牌自 v4 起已弃用,您应该使用Type<T>or InjectionToken<T>instance 代替
  • create(providers: StaticProvider[], parent?: Injector)(函数参数)自 v5 以来已弃用,您应该使用新签名Injector.create(options)

    create(options: {providers: StaticProvider[], parent?: Injector, name?: string})
    

更新了 STACKBLITZ


推荐阅读