angular - 将值注入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上找到
解决方案
因此,在您的情况下,请执行以下操作:
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>
orInjectionToken<T>
instance 代替 create(providers: StaticProvider[], parent?: Injector)
(函数参数)自 v5 以来已弃用,您应该使用新签名Injector.create(options)
:create(options: {providers: StaticProvider[], parent?: Injector, name?: string})
推荐阅读
- javascript - 在没有 .env 文件的情况下构建反应后设置 env 变量
- matlab - Matlab中的牛顿法
- c# - c#将方法传递给参数以进行日志记录
- php - codeigniter mysql 位运算符
- angular - 修改输入值并突出输入字段后防止自动提交
- android - Play Games Multiplayer 中的等候室不显示已连接的玩家
- arrays - 如何在 BigQuery 中连接两个不同数据类型的数组?
- c# - 通过 CLR/CLI 在 C++ 和 C# 之间共享值
- wordpress - 将 HTTP/S SSL 添加到 WP 一键部署 GCP:响应时间过长
- c# - 如何使用 Microsoft Graph API 按自定义列值查找 SharePoint 文档