How to use variable inside JSON file via Angular?

600 Views Asked by At

I want to assign value of ${field.formControl.value} to a variable inside my JSON object which is {{fieldName}}. Here's my JSON Object:

{
    "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]",
            }
        }
    }
}

I am usig ngx-formly to build dynamic forms and I want to show dynamic language based errors. How do I assign value to {{fieldName}} which is in my JSON?

Here's how I am making dynamic formly object.

control comes from forEach Loop 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]}`,
    }
}
1

There are 1 best solutions below

0
On

Okay, here's how I figured it out: By passing translate.stream('MY_PATH', {fieldName: field.templateOptions.label })

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

            }
          },

In similar way, you can pass any number of params you want.