【问题标题】:Injecting values into a dynamic component in Angular将值注入Angular中的动态组件
【发布时间】:2018-10-08 19:33:34
【问题描述】:

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

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

值因规则而异,因此我尝试在注入器中使用 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

【问题讨论】:

    标签: angular dependency-injection


    【解决方案1】:

    您需要在动态组件中get 传递值。见official example

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

    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;
        }
      }
    }
    

    还请注意

    • string 令牌自 v4 起已弃用,您应使用 Type<T> 或 改为InjectionToken<T> 实例
    • create(providers: StaticProvider[], parent?: Injector)(函数 arguments) 自 v5 起已弃用,您应该使用新的 签名Injector.create(options)

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

    更新STACKBLITZ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2018-01-12
      • 1970-01-01
      • 2020-01-06
      • 2016-06-10
      • 2017-05-20
      • 2018-12-31
      相关资源
      最近更新 更多