Ngx-formly: Dynamic Forms in array Angular 9 with help of ngx-formly

Created on 4 Jul 2020  ·  25Comments  ·  Source: ngx-formly/ngx-formly

Need help. Here's the simple story:
Trying to achieve: Dynamic Forms as per user selected locale JSON.
Using: ngx-formly/material.
Problem: How to map variable fields with my array of objects this.fields2?

Code: in my component.ts file I have:

model: any = {};
options: FormlyFormOptions = {};
fields: FormlyFeildCongif[];

Fetching the JSON of the selected Locale:
 ngOnInit():void
{
    this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(
    (res) =>
    {
        this.myDynamicForm = res.yBank.fields;
        this.dynamicFormCreate(this.myDynamicForm);
    });
}

public dynamicFormCreate(arr:any)
{
    for(let i=0; i< arrr.length; i++)
    {
        //here I am fetching data from JSON and creating an Object structure which is accepted by formly fields.
        //the problem is how do I map this.fields2 array of objects with the formly fields.
        this.fields2.push(
        {
            key: arr[i].type,
            type: arr[i].type,
            templateOptions:
            {
                label: arr[i].label,
                placeHolder: arr[i].placeHolder,
                description: arrp[i].description,
                required: true
            }
        });
    }
}

my component.html

<form [formGroup]="myForm"> <formly-form [model]="model [fields]="fields" [options]="options" [form]="myForm"> </formly-form> </form>

question

All 25 comments

@juristr Can you please help?

Is this actual code? Because the "length" is wrongly spelled here:

arrr.lenght

Heyy Hi,

Thank you so much for replying!! I was watching your videos on YouTube
regarding ngx-formly.

That's a typing mistake. I'm in a hurry to resolve the dynamic form issue.
In multiple components under material steppers. That's somewhat like the
actual code. Please ignore the typo. All I want to know is how can I
associate the array of objects I am creating to fields: FormFieldConfig[];

On Sat, Jul 4, 2020 at 5:24 PM Juri Strumpflohner notifications@github.com
wrote:

Is this actual code? Because the "length" is wrongly spelled here:

arrr.lenght


You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/ngx-formly/ngx-formly/issues/2351#issuecomment-653756513,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AI3W7GZTGZ34FT3VLZIHPULRZ4J7BANCNFSM4OQKNGYA
.

Could you suggest an alternative solution by how can I push objects into this.fields. Or any possible solution?
When I directly insert the objects I'm creating into this.fields, I am getting an error Cannot read property 'map' of undefined.

@aitboudad didn't help. Can you illustrate with my attached code above?

@injurioustohealth the question is not clear enough and don't expect from us to understand your issue without further details :pray: also could please replicate your example using our starter example https://stackblitz.com/edit/ngx-formly-ui-bootstrap.

@injurioustohealth the question is not clear enough and don't expect from us to understand your issue without further details 🙏 also could please replicate your example using our starter example https://stackblitz.com/edit/ngx-formly-ui-bootstrap.

I am late but I solved it out by just using a *ngIf on my form

<form [formGroup]="myForm" *ngIf="fields">
<formly-form
[model]="model
[fields]="fields"
[options]="options"
[form]="myForm">
</formly-form>
</form>

But there again I have a question: How can I change the colour of a field whose input is valid? Also, how can I use NgxMatIntlTelInput for phone number validation country-wise in my ngx-formly form?

how can I use NgxMatIntlTelInput for phone number validation country-wise in my ngx-formly form?

create a custom field type https://formly.dev/guide/custom-formly-field and use form-field as a wrapper in case you're using our UI

@NgModule({
  imports: [ 
    FormlyModule.forRoot({
      types: [{
        name: 'phone',
        component: PhoneTypeComponent,
        wrappers: ['form-field'],
      }]
    }),
  ],
})
export class AppModule { }

How can I change the colour of a field whose input is valid?

Rely on the ng-valid class which is added to the field when is valid

@aitboudad will it be under expressionProperties ?
expressionProperties: {
'templateOptions.color' : "form.valid ? 'primary' : 'warn"
},

Possible but I would prefer to keep it simple and rely on a global config.

expressionProperties: {
  'templateOptions.color' : "field.formControl.valid ? 'primary' : 'warn'"
},

Thank You...I got 80% of problems resolved with the help of formly. Solving a bunch of remaining ones. 🥇

How to add [stepControl] in ngx-formly multi-step form?

<mat-step *ngFor="let step of steps; let index = index; let last = last;">
      <ng-template matStepLabel>{{ step.label }}</ng-template>
      <formly-form
        [form]="form.at(index)"
        [model]="model"
        [fields]="step.fields"
        [options]="options[index]">
      </formly-form>

      <div>
        <button *ngIf="index !== 0" matStepperPrevious class="btn btn-primary" type="button" (click)="prevStep(index)">Back</button>
        <button *ngIf="!last" matStepperNext class="btn btn-primary" type="button" [disabled]="!form.at(index).valid" (click)="nextStep(index)">Next</button>
        <button *ngIf="last" class="btn btn-primary" [disabled]="!form.valid" type="submit">Submit</button>
      </div>
<ng-container *ngFor="let step of steps; let index = index; let last = last;">
  <mat-step [stepControl]="form.at(index)">
    ...
  </mat-step>
</ng-container>

Note: There is another approach to manage stepper through a custom field type which you may check:
https://stackblitz.com/edit/angular-yu7bzv-uucyxg

Hello again,

I have a sort of different requirement with my project where I have to show language-specific errors coming from JSON Here's an example for English and German.

Here's my JSON response I am provided with:

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

    --------------------------
    {
        "sectionA":
        {
            "error":
            {
                "allZeros":"Alle Nullen sind nicht erlaubt.",
                "required" : "{{fieldName}} Wird benötigt."
                "patternErrors":
                {
                    "userAccountFirstName":"{{fieldName}} Ungültiger Name. Bitte geben Sie [A-Z a-z] ein",
                    "userAccountLastName":"{{fieldName}} Ungültiger Nachname. Bitte geben Sie [A-Z a-z] ein",
                }
            }
        }
    }

control comes from forEach Loop fields.forEach(control,index)

My FormlyFieldConfig object is like below where I'm dynamically pushing the myObject into FormlyFields Array:

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]}`,
        }
    }

How can I associate field.templateOptions.label with {{fieldName}} in JSON? Could you suggest me any clean way to show language-specific errors?

For i18n check the demo example https://formly.dev/examples/advanced/i18n

Thanks, I checked that example. Also, (https://github.com/ngx-formly/ngx-formly/issues/1368) and
https://github.com/ngx-formly/ngx-formly/issues/2140

Yet, I am not able to bind my variable which is inside my JSON {{fieldName}}. I want to use [translateParams] in my validation messages. translate.steam or translate.instant didn't help.

Normally it should work by passing params through the second argument of translate.steam, could you please provide a reproduction example using stackblitz?

Goddddddd!! I can't believe, got it somewhat working just moments ago:
Check it out here: https://stackblitz.com/edit/angular-kgzvzp-ryerxj?file=src%2Fapp%2Fapp.component.ts

But I want to add more variables like min length. How do I do that?

The same way I think :thinking: and since you're using JSON you may consider using custom extension which is a generic way to translate all your forms https://formly.dev/examples/advanced/i18n-alternative

I'm trying to achieve it. A BIG THANK YOUUUUU

@aitboudad Quick query: Is it mandatory to pass the path in single inverted comma inside like translate.stream('FORM.VALIDATION.REQUIRED' , {fieldName: field.templateOptions.label}).
It won't work if I pass my JSON response under it. like: translate.stream(this.myJSONresponse.error.required , {fieldName: field.templateOptions.label})

ngx-translate will deal with the loading part so you should pass sectionA.error.required, if you want to just deal with the binding part then you don't have to rely on ngx-translate just resolve the binding part using interpolate fucntion https://github.com/ngx-translate/core/blob/master/projects/ngx-translate/core/src/lib/translate.parser.ts#L26

Was this page helpful?
0 / 5 - 0 ratings