Git Product home page Git Product logo

angular-dynamic-forms's Introduction

Angular Dynamic Forms

Angular component that allows the creation of dynamic forms. You can use this component in situations where you get the configuration for the form from an external API or if you just hate HTML ๐Ÿ˜€

Angular dynamic form img

List of features

UI Style โ€” for UI I used PrimeNG but you can use any Angular UI Library.

Grid layout โ€” for grid I used PrimeFLEX

  • ๐Ÿฆพ Dynamically created form only from JSON configuration
  • ๐Ÿ˜Ž Full gird layout for forms
  • ๐Ÿค– Dummy fields without UI input fields
  • ๐Ÿ€ You can group fields in same column
  • ๐Ÿ’ฅ Validation error messages
  • ๐Ÿ’ฅ Custom patterns for field value & custom error messages
  • ๐Ÿ— Responsive forms
  • ๐Ÿ‘‡ Easy to add more supported fields

Supported fields by default

You can add more by yourself!

Field Selector / controlType Description
Input input Text input field.
Textarea textarea Textarea field.
Dropdown dropdown Dropdown field.
Checkbox checkbox Checkbox field.

Installation

Clone repo and run:

npm install
ng serve -o

Usage

There are two ways you can use dynamic forms. The first way is if you have no additional controls other than those in the configuration.

Import module

You can copy the entire form-factory folder into your project and then import FormFactoryModule in app.module.ts

  FormFactoryModule.forRoot({
    fields: [],
  }),

Example 1

  constructor(
    public formFactory: FormFactoryService
  ) {}

  ngOnInit(): void {
    /**
    * Call formFactory service and pass form fields
    * JSON configuration to create new form group
    */
    this.exampleForm = this.formFactory.createForm(this.exampleFields);
    /**
    * Example how to add additional formControl
    * to form ifyou need
    */
    this.exampleForm.addControl('id', new FormControl(1, Validators.required));
  }
  <app-form-factory
    [form]="exampleForm"
    [fields]="exampleFields"
  ></app-form-factory>

Example 2

If you want to insert dynamic fields into one control and add the rest of the field via the form builder, you can do so as follows.

  constructor(
    private fb: FormBuilder,
    public formFactory: FormFactoryService
  ) {}

  ngOnInit(): void {
    this.exampleForm = this.fb.group({
      dynamic: this.formFactory.createForm(this.exampleFields),
      id: ['1', Validators.required],
    });
  }
  <app-form-factory
    [form]="formFactory.getFormGroup(exampleForm,'dynamic')"
    [fields]="exampleFields"
  ></app-form-factory>

Available configuration

Configuration for exsisting fields

General config options description:

Option Description
controlType Selector for your form field
colSize Look at primeflex documentation to see all grid layout classes - PrimeFLEX
options This options is used to create form field
containerClass You can add custom CSS class to field container
label Form field label
placeholder Form field placeholder
formControlName Angular reactive forms control name
value Default value for form field
disabled Define is field disabled
required Define is field required
maxLength Define field max length
pattern Regex pattern for field

Input field

  • controlType: input
{
  "controlType": "input",
  "colSize": "col-12 sm:col-4",
  "options": {
    "containerClass": "mb-0", // Optional
    "label": "Title",
    "placeholder": "Enter title", // Optional
    "formControlName": "title",
    "value": "", // Optional - default is ''
    "disabled": false, // Optional
    "validators": {
      // Optional
      "required": true,
      "maxLength": 200
    }
  }
}

Textarea field

  • controlType: textarea
Option Description
rows Number of textarea rows
{
  "colSize": "col-12 sm:col-3",
  "controlType": "textarea",
  "options": {
    "containerClass": "mb-0", // Optional
    "label": "Description",
    "placeholder": "My description", // Optional
    "formControlName": "description",
    "value": "", // Optional - default is ''
    "rows": 5, // Optional
    "disabled": false, // Optional
    "validators": {
      // Optional
      "required": true,
      "maxLength": 200
    }
  }
}

Dropdown field

  • controlType: dropdown
Option Description
optionValue The value to be displayed when selected
optionLabel The label to be displayed when selected
dropdownOptions Array with options
value Default value
{
  "colSize": "col-12",
  "controlType": "dropdown",
  "options": {
    "label": "List",
    "placeholder": "Chose", // Optional
    "formControlName": "someList",
    "optionValue": "value",
    "optionLabel": "label",
    "dropdownOptions": [
      {
        "label": "Item 1",
        "value": 1
      }
    ],
    "value": []
  }
}

Checkbox field

  • controlType: checkbox
{
  "colSize": "col-12 sm:col-3",
  "controlType": "checkbox",
  "options": {
    "label": "Remember me",
    "formControlName": "remember",
    "value": true // Optional
  }
}

Custom regex pattern

errorMessage - This message will be displayed if pattern not matched.

{
  "controlType": "input",
  "colSize": "col-12 sm:col-4",
  "options": {
    ...
    "errorMessage": "Please enter a number from 1 to 9",
    "validators": {
      "pattern": "^[0-9]*$", // Any regex pattern
      "required": true,
      "maxLength": 200
    }
  }
}

Dummy fields

This fields doesn`t have UI representation, they just exist in angular form builder.

  [
  ...
  {
    "dummyFields": [
      {
        "options": {
          "formControlName": "dummyField",
          "value": "Hello!",
        },
      },
      {
        "options": {
          "formControlName": "myId",
          "value": "",
        },
      },
    ],
  },
  ...
  ]

Group fields in grid layout

This is example configuration from the image at the top of the documentation. Use group array to pass all the fields you want to be in the same column. Inside group you don't need to define colSize option because it is already defined for the whole group.

fields:FormFactoryModel[] = [
  {
  "colSize": "col-12 sm:col-4",
  "group": [
    {
      "controlType": "input",
      "options": {...}
    }
    {
      "controlType": "input",
      "options": {...}
    }
  ]
},
{
  "colSize": "col-12 sm:col-4",
  "controlType": "textarea",
  "options": {...}
},
{
  "colSize": "col-12 sm:col-4",
  "group": [
    {
      "controlType": "dropdown",
      "options": {...}
    }
    {
      "controlType": "checkbox",
      "options": {...}
    }
  ]
}
]

Add more fields

This system supports some form fields by default (see above). If you want to add fields you can do that in forRoot({}) configuration:

  @NgModule({
    declarations: [...],
    imports: [
      ...
      FormFactoryModule.forRoot({
        fields: [
          {
            type: 'my-custom-field',
            component: MyCustomFieldComponent
          }
        ],
      }),
    ],
    ...
  })
  export class AppModule {}

IMPORTANT - If you want to add your custom field please open some of exsisting form-fields in form-factory/components/form-fields folder and follow the same component structure.

Note that if you want you can pass any form field you created like in example above.

type - Selector that you use for controlType option in JSON configuration.

component - Angular component

Contributing

If you want to contribute to a project and make it better, your help is very welcome. Contributing is also a great way to learn more about social coding on Github, new technologies and and their ecosystems and how to make constructive, helpful bug reports, feature requests and the noblest of all contributions: a good, clean pull request.

About me

Linkedin ๐Ÿ‘‹ Instagram
Martin S. @maki.stf

angular-dynamic-forms's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

angular-dynamic-forms's Issues

Display Errors on Submit

Hi @martinstefanovic wonderful code base for those who are working with Dynamic forms. But how to handle to display the errors on submit before entring any values, cuz the errors are triggered only when there is a change in the input, so basically the form loads and the users clicks on submit, how to handle it.

Thanks in advance.

onChange(event: Event) {
    const formGroup = this.controlContainer.control as FormGroup;

    this.errors = formGroup.controls[this.options.formControlName].errors;
    if (this.errors) {
      this.errors.errorMessage = this.options?.errorMessage;
    }
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.