1.14.36 • Published 4 years ago

@gordon_freeman/ez-form v1.14.36

Weekly downloads
106
License
GNU GPL V3.0
Repository
github
Last release
4 years ago

ez-form

Index

  1. Description
  2. Install
  3. Usage 3.1 Files 3.2 Multiple files 3.3 Autocomplete 3.4 Toaster 3.5 Bootstrap 3.6 Animations
  4. Summary

  5. Especial Thanks

Description

ez-form is a component that allows create reactive forms for angular 2+.

This library makes use of angular material, bocd otstrap and PrimeNG libraries and components

Install

  • Install the package:

    $ npm i @gordon_freeman/ez-form  

You must have bootstrap installed in your angular project

  • Import EzFormModule

    @NgModule({  
      declarations: [  
        AppComponent  
      ],  
      imports: [  
        EzFormModule,  
      ],  
      providers: [],  
      bootstrap: [AppComponent]  
    })  

Usage

First we need a config object inside of parent component.

For example: we need to create a form with the following fields:

  • UUID: Disabled input (Optional)
     uuidField: InputTextFieldInterface = {
       controlName: 'uuid',
       type: {
         typeName: 'input-text'
       },
       disabled: true,
     };
  • Password: Password input (Required)
      passwordField: InputTextFieldInterface = {
        controlName: 'password',
        type: {
          typeName: 'input-text',
          class: 'password',
        },
        validators: [
          Validators.required,
        ]
      };
  • Brithday: Date input (Required)
  birthdayField: DateFieldInterface = {
    controlName: 'birthday',
    placeholder: 'Enter your birthday date',
    hint: 'Enter a valid date',
    type: {
      typeName: 'date'
    },
    validators: [
      Validators.required,
    ]
  };
  • Address: Long text input (Required)
  addressField: TextAreaFieldInterface = {
    controlName: 'address',
    label: 'Address',
    placeholder: 'Enter a complete address',
    type: {
      typeName: 'textArea',
      maxLength: 20,
    },
    validators: [
      Validators.required,
    ],
  };
  • Email: Text input (Required, Email Validation)
  emailField: InputTextFieldInterface = {
    controlName: 'email',
    validators: [
      Validators.required,
      Validators.email
    ],
    placeholder: 'Enter an email',
    type: {
      typeName: 'input-text',
      maxLength: 30,
    },
    errorMessages: {
      required: 'The email is mandatory',
      email: 'You must enter a valid email',
    },
    hint: 'Enter a valid email'
  };
  • Civil State: Select input (Required)
  civilStateField: SimpleSelectFieldInterface = {
    controlName: 'civilState',
    placeholder: 'Choose a civil state',
    label: 'Civil state',
    hint: 'Please pick a Civil State',
    validators: [
      Validators.required
    ],
    type: {
      typeName: 'select',
      options: [
        {
          value: 1,
          label: 'Married'
        },
        {
          value: 2,
          label: 'Single'
        }
      ]
    },
  };
  • Cities: Multiple Select input (Required, minimum 2)
  citiesField: CheckFieldInterface = {
    controlName: 'cities',
    type: {
      typeName: 'check',
      minRequired: 2,
      options: [
        {
          value: 1,
          label: 'Quito'
        },
        {
          value: 2,
          label: 'Cuenca'
        },
        {
          value: 3,
          label: 'Ambato'
        }
      ]
    },
    label: 'Cities',
    errorMessages: {
      required: 'select two cities at least',
    }
  };
  • Favorite Fruit: Radio Button input (Required)
          favoriteFruitField: RadioFieldInterface = {
            controlName: 'favoriteFruit',
            validators: [
              Validators.required
            ],
            label: 'Favorite Fruit',
            type: {
              typeName: 'radio',
              options: [
                {
                  value: 3,
                  label: 'Apple'
                },
                {
                  value: 1,
                  label: 'Pear'
                },
                {
                  value: 2,
                  label: 'Pineapple'
                }
              ],
            },
          };
  • Profile Picture: File input (Accept images only)
  profilePictureField: FileFieldInterface = {
    controlName: 'profilePicture',
    label: 'Profile Picture',
    hint: 'Please upload your profile picture',
    placeholder: 'Add your profile picture',
    validators: [
      Validators.required,
      FileValidator.extensions(['jpg']),
      FileValidator.minSize(100),
      FileValidator.maxSize(500),
    ],
    errorMessages: {
      required: 'Mandatory File',
      fileExtension: 'Please select a jpg file',
      fileMinSize: 'File size must be above of 100 kilobytes',
      fileMaxSize: 'File size is larger than 500 kilobytes'
    },
    type: {
      typeName: 'file',
      multiple: false,
      accept: 'image/*',
      showFile: true,
    },
  };
  • someFields: File input (Multiple)
    • Validators: Required, minSize, maxSize, file extension.
  someFilesField: FileFieldInterface = {
      controlName: 'someFiles',
      label: 'Pictures',
      hint: 'Please upload your files',
      placeholder: 'Add Files',
      validators: [
        Validators.required,
        FileValidator.extensions(['png']),
        FileValidator.maxSize(500),
      ],
      errorMessages: {
        fileExtension: 'Please select png files only',
        required: 'Mandatory File',
        fileMaxSize: 'File size is larger than 500 kilobytes'
      },
      type: {
        typeName: 'file',
        multiple: true,
        accept: '*/*',
        showFile: true,
        tableHeaders: {
          actions: 'Operations',
          description: 'Entry Files'
        }
      },
    };

All fields must be at a config array like this in our parent component, for example:

parentComponent.ts

myConfiguration: PrincipalFormFieldInterface[] = [
    this.uuidField,
    this.passwordField,
    this.birthdayField,
    this.addressField,
    this.emailField,
    this.civilStateField,
    this.citiesField,
    this.favoriteFruitField,
    this.profilePictureField,
    this.someFilesField,
  ];

So in our parentComponent.html call the component.

    <ez-form
            [formConfig]="myConfiguration"
          >
          <button [disabled]="!usuario" class="btn btn-block btn-info">Submit</button>
    </ez-form>

If we want our form to be filled with default values. We need to declare a object with the controls name as keys example:

    userData = {
        uuid: 1234,
        email: 'juan.pecados@mail.com',
        civilState: 1,
        otherDate: '2015-02-16',
        birthday: '1999-02-16',
        favoriteFruit: 1,
        cities: [1, 3],
        password: '12133',
      };

Template parentComponent.html:

    <ez-form
            [formConfig]="myConfiguration"
            [inputData]="userData"
          >
          <button [disabled]="!usuario" class="btn btn-block btn-info">Submit</button>
    </ez-form>

The form has an Output where you will return the form data or anundefined depending If the form has been filled out correctly.

So we need to make use of the Output : dataFromForm"

    <ez-form   
            [formConfig]="myConfiguration"  
            [inputData]="userData"  
            (dataFromForm)="someFunction($event)"  
            >  
         <button (click)="someFunction()">Submit</button>  
     </ez-form>  

Results:

formulario

File

Multiple Files

files

Autocomplete

Parent component typescript code:

    articleField: AutoCompleteFieldInterface = {
        controlName: 'article',
        validators: [
          Validators.required
        ],
        label: 'Wikipedia article',
        placeholder: 'Example: DNA',
        type: {
          typeName: 'autoComplete',
          completeMethod: this.filterWikipediaArticleByTitle,
          showAttribute: 'title',
          componentReference: this,
        },
        errorMessages: {
          required: 'The article is mandatory',
        },
        hint: 'Search an article'
      };

    filterWikipediaArticleByTitle(event, contexto) {
        return contexto._wikipediaService.find(event.query ? event.query : event);
      }

About filter method

    The filter service methond must return an observable. If you need format the data from the API, 
    you should use the `pipe` operator.

The find method code in wikipedia service:

    find(query: string): Observable<any> {
        const url = `${this.url}&srsearch=${query}`;
        return this._httpClient.get(url)
        .pipe(
          mergeMap(
            (response: any) => {
              if (response.query) {
                return of(response.query.search);
              }
              return of([]);
            }
          )
        );
      }

Results

  • Material

autocomplete-material

  • PRIMENG
I put the PRIMENG autocomplete into bootstrap mode since the boostrap framework does not have an autocomplete component.

autocomplete-primeng

Toaster

This library makes use of angular2-toaster

  • The toaster is the message which shows on screen when the form has been filled correctly or incorrectly.
  • The display of this messages could be optional

We need to make use of the following Input : showToaster"

<ez-form
        [formConfig]="myConfiguration"
        [inputData]="userData"
        [showToaster]="false"
      > ... 

Also we could config the messages that will show on the toaster:

    myToasterConfig = {
        success: {
          type: 'info',
          title: 'GOOD',
          body: 'All right!!'
        },
        fail: {
          type: 'warning',
          title: 'BAD',
          body: 'Someting was wrong!!'
        }
      };

Use the input : toasterConfig"

    <ez-form
            [formConfig]="myConfiguration"
            [inputData]="userData"
            [toasterConfig]="myToasterConfig"
          >...

Results:

formulario

Bootstrap

By Deault the ez-form component loads its internal components from Angular Material.

  • If you want make use of bootstrap components:

Use the Input : styleFramework"

    <ez-form
            [formConfig]="myConfiguration"
            [inputData]="userData"
            [styleFramework]="'material'"
          >..

Results

resultadoBootstrap

Animations

The error messages animations for every form field could be modify, so we need to make use of animate.css .

Use the Input : msgErrorAnimation:

<ez-form
        [formConfig]="myConfiguration"
        [inputData]="userData"
        [msgErrorAnimation]="'fadeInLeft'"
      >

Complete example form component:

    <ez-form
            [formConfig]="myConfiguration"
            [inputData]="userData"
            (dataFromForm)="someFunction($event)"
            [styleFramework]="'material'"
            [msgErrorAnimation]="'fadeInLeft'"
            [toasterConfig]="myToasterConfig"
          >
            <button [disabled]="!userData" class="btn btn-block btn-info">Submit</button>
          </ez-form>

Summary

Component

AttributeTypeDescriptionRequired
formConfigInputForm config objectYES
inputDataInputForm default values objectOPTIONAL
dataFromFormOutPutData returned from formYES
styleFrameworkInputForm styleOPTIONAL
msgErrorAnimationInputError message animationOPTIONAL
toasterConfigInputToaster message configuration objectOPTIONAL
showToasterInputShow Toaster messageOPTIONAL
fullWidthInputFull width of each form fieldsOPTIONAL

Control Object

AttributeDescriptionRequired
controlNameForm Control nameYES
placeholderDescribes the expected value of an input fieldOPTIONAL
hintHint displayed in the input field before the user enters a valueOPTIONAL
labelHint displayed in the input field before the user enters a valueOPTIONAL
typeInput type object: select, input, file, check..YES
validatorsArray with angular form validators, it doesn't work with check typeOPTIONAL

Type Attribute Object

AttributeDescription
inputInput field for text and numbers
typenametype name: input, select, radio, check, textarea, date, file
classUniquely for input type. Defines the character type for example a password field
optionsUniquely for select, radio, check
minRequiredUniquely for check. Defines how many checks fields are mandatory
maxLengthUniquely for input, textarea and date. Defines how many characters are allowed
showFileUniquely for file. Default false. Show file or files preview.

Example Full Code

If you are looking for a full example of this library please check the following github repository

Especial Thanks

1.14.34

4 years ago

1.14.35

4 years ago

1.14.36

4 years ago

1.11.33

4 years ago

1.11.32

4 years ago

1.11.31

4 years ago

1.10.31

4 years ago

1.10.29

4 years ago

1.10.30

4 years ago

1.10.28

4 years ago

1.10.27

4 years ago

1.10.26

4 years ago

1.10.25

4 years ago

1.10.24

4 years ago

1.10.22

4 years ago

1.10.23

4 years ago

1.10.21

4 years ago

1.10.20

4 years ago

1.10.19

4 years ago

1.10.18

4 years ago

1.10.17

4 years ago

1.10.16

4 years ago

1.10.15

4 years ago

1.8.15

4 years ago

1.8.14

4 years ago

1.8.12

4 years ago

1.8.11

4 years ago

1.8.10

4 years ago

1.8.9

4 years ago

1.7.9

4 years ago

1.6.8

4 years ago

1.6.7

4 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.2.2

4 years ago

1.0.0

4 years ago

0.6.17

4 years ago

0.4.17

4 years ago

0.4.16

4 years ago

0.4.15

4 years ago

0.2.15

4 years ago

0.2.14

4 years ago

0.2.12

4 years ago

0.2.11

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.1

4 years ago