javascript - 如何通过 Angular 在 JSON 文件中使用变量?
问题描述
我想将值${field.formControl.value}
赋给我的 JSON 对象中的一个变量,即{{fieldName}}
. 这是我的 JSON 对象:
{
"sectionA": {
"error": {
"allZeros": "All Zero's not allowed.",
"required": "{{fieldName}} is required.",
"patternErrors": {
"userAccountFirstName": "{{fieldName}} Invalid Name. Please enter [A-Z a-z]",
"userAccountLastName": "{{fieldName}} Invalid Lastname. Please enter [A-Z a-z]",
}
}
}
}
我正在使用ngx-formly
构建动态表单,并且我想显示基于动态语言的错误。如何{{fieldName}}
为我的 JSON 中的值分配值?
这是我制作动态形式对象的方式。
控制来自 forEach 循环fields.forEach(control,index)
myObject =
{
'key': control.name,
'type': 'input',
'templateOptions':
{
'label': control.label,
'pattern': control.validation.pattern,
'required': true
}
'validation':
{
'required': (error, field: FormlyFieldConfig) => `${field.templateOptions.label} ${myJSONresponse.error.required}`,
'pattern': (error, field: FormlyFieldConfig) => `"${field.formControl.value}" ${myJSONresponse.error.patternErrors[control.name]}`,
}
}
解决方案
好的,我是这样想的:通过 translate.stream('MY_PATH', {fieldName: field.templateOptions.label })
validation:
{
messages:
{
required: (error, field: FormlyFieldConfig) => this.translate.stream('sectionA.error.required', {fieldName: field.templateOptions.label}),
}
},
以类似的方式,您可以传递任意数量的参数。
推荐阅读
- node.js - 如何获取列表 nodejs 进程/应用程序端口和路径?
- r - 如何从 ggplot2 中的两个分类变量创建 x 轴标签?
- python - 如何在 Django Rest 中建立序列化程序之间的关系?
- kotlin - 如何使用 kotlin 和 junit 用 MockK 模拟 HashMap?
- algorithm - 具有罗宾斯定理的强方向图算法
- java - 如何使用用户输入在 Java 中的 Class 和 TestClass 中创建多维数组
- java - 在运行时查询 servlet 上下文
- angular - 如何将 XML 数据集导入我的 Laravel 项目的数据库
- reactjs - TypeScript 泛型:React 中具有联合类型的道具
- python - 比较两个文件并删除重复的数字python