首页 > 解决方案 > 如何通过 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]}`,
    }
}

标签: javascriptjsonangulartypescriptngx-formly

解决方案


好的,我是这样想的:通过 translate.stream('MY_PATH', {fieldName: field.templateOptions.label })

 validation:
          {
            messages:
            {
              required: (error, field: FormlyFieldConfig) => this.translate.stream('sectionA.error.required', {fieldName: field.templateOptions.label}),

            }
          },

以类似的方式,您可以传递任意数量的参数。


推荐阅读