Creating and duplicating forms with Formly

Applications often require forms that collect visitor information. Some applications require more than a single form, and it is tedious to repeat the HTML code for each form, especially if they are similar forms.

This post will show how you can build and duplicate dynamic forms using Angular Formly and save development time and effort.

Step 1: Install the Formly library

ng add @ngx-formly/schematics --ui-theme=bootstrap

The ui-theme is an optional flag. The other options are,

  1. bootstrap
  2. material
  3. ionic
  4. primeng
  5. kendo
  6. nativescript

After the installation, you need to import the module,

@NgModule({
 imports: [
   FormlyModule.forRoot(),
   FormlyBootstrapModule // if boostrap option is selected
   FormlyMaterialModule,// if material option is selected
 ],
})

We need the forRoot() at the application root level. This method accepts the passing of a config argument as an extra config. The extra config may contain values that define how to register the custom field type, validation for the form, etc. 

Step 2: Add Formly inside your component

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

The <formly-form> component is the main container of the form, that will build and render the form fields. It accepts the following inputs:

  1. fields: The field configurations for building the form.
  2. form: The form instance which allows tracking model value and validation status.
  3. model: The model to be represented by the form.

Step 3: Configure the form

form = new FormGroup({});
model = {};
fields: FormlyFieldConfig[] = [
 {
   key: 'name',
   type: 'input',
   templateOptions: {
     label: 'Your Name',
     placeholder: 'Enter your full name',
     required: true,
   }
 }
];
  • key: form control name 
  • type: type of the field like input, select, checkbox, etc
  • templateOptions:
  • label: Label for the fields
  • placeholder: Placeholder for the field (optional)
  • required: boolean (optional)

Validation 

In the above code snippet, we see that the Formly library also supports additional validation such as min, max, minLength, maxLength, etc. We can also do custom validation. To do so, we need to include the validators property in the form fields.

validators: {
  name: {
     expression: c => !c.value || c.value.length <= 10,
     message: (error, field: FormlyFieldConfig) =>
              'Label should be less than 10 character'
  }
}

Use Of Observable

When using the forms, we have to use the select box and show the options for it. We may need to hard code the option values but may also fetch these values from the API. Here we will see how to fetch the values from the API.

fields: FormlyFieldConfig[] = [
   {
     key: 'sport',
     type: 'select',
     templateOptions: {
       label: 'Sport',
       options: this.dataService.getSports(),
       valueProp: 'id',
       labelProp: 'name',
     },
   },
 ];
constructor(private dataService: DataService) {}

In the above code, FormlyFieldConfig is for the field configurations for building the form. In the constructor, we must inject the service.

In the service.ts file, we have to add the method,

sports = [
       { id: '1', name: 'Soccer' },
       { id: '2', name: 'Basketball' },
   ];
   getSports(): Observable<any[]> {
       return of(this.sports);
   }

Conclusion

Formly helps create and duplicate forms in our application. Validation and use of Observables are the most crucial things while developing the forms and Formly can handle these easily. 

Learn More about Encora

We are the software development company fiercely committed and uniquely equipped to enable companies to do what they can’t do now.

Learn More

Global Delivery

READ MORE

Careers

READ MORE

Industries

READ MORE

Related Insights

How Can Enterprise Media Companies Optimize Avid API Integration for Scalable Workflows?

Optimize Avid API integration to enhance media workflows, automate processes, and scale operations ...

Read More

3 Ways AI Creates Streamlined Conversion Pathways in Digital Retail

Automated pricing solutions now analyze billions of scenarios simultaneously, delivering profit ...

Read More

Next-Generation Core Banking: Creating Intelligent Financial Services with Data, Cloud and AI

Discover how data, cloud, and AI are transforming core banking. Learn how banks can modernize their ...

Read More
Previous Previous
Next

Accelerate Your Path
to Market Leadership 

Encora logo

Santa Clara, CA

+1 669-236-2674

letstalk@encora.com

Innovation Acceleration

Speak With an Expert

Encora logo

Santa Clara, CA

+1 (480) 991 3635

letstalk@encora.com

Innovation Acceleration