0.3.7 • Published 7 years ago

angular2-easy-forms-enterthusiast v0.3.7

Weekly downloads
5
License
MIT
Repository
github
Last release
7 years ago

Angular 2 Easy Forms - Enterthusiast

Is a library for simplification of forms in Angular 2. Its meant for quick creation of forms and form validation.

The library is inspired by angular.io dynamic forms.

You can find a live example here

Angular 2 Easy Forms is a lib made by Filip Lauc

Enterthusiast humbly modified it for his needs, will continue to update if new needs arise. Hope it can help other modify and get the most of this really cool lib!

Modifications by @enterthusiast

  • Radio and Checkboxes now work with <input id='foo'> and their matching <label for='foo'>, allowing the user to click the text to check.
  • Add typescript on the main project, making it easier to build the lib.
  • Consequently add the Build paragraph to README.md explaining how to compile the lib.
  • Workaround a typescript compilation artifact for data.interface.ts. The resulting js was trying to export nothing, making the app crash. Add a fake and empty component export.
  • Added multiple option to add classes everywhere in the form, it works well with bootstrap
  • Add some Boostrap logic/classes for validation feedback, you can enable the bootstrap theme by uncommenting customTheme: 'ng2Bootstrap3' in the example app.component.ts file. More about ng2-boostrap.

Documentation

  1. Setup
  2. Questions
  3. Validation
  4. Events
  5. Settings
  6. Build

Setup

You can install the library from npm with the following command:

npm install --save angular2-easy-forms-enterthusiast

Import the EasyFormsModule in your app.module. You also need to have the FormsModule imported for the library to work.

@NgModule({
    imports: [
        BrowserModule,
        EasyFormsModule
    ],
    providers: [],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}

Then you define a list of questions as well as a settings and classes object if required and pass it to the component.

@Component({
    selector: 'app',
    template: `
        <easy-form [easyFormData]="data" (onSubmit)="onSubmit($event)" (onChanges)="onChanges($event)"></easy-form>
    `
})
export class AppComponent {
    constructor() {}

    public data = {
        settings: {
            submitButtonText: 'Send',
        },
        classes: {
            form: 'some-class',
            submit: ['class-one', 'class-two']
        },
        questions: [
            {
                type: 'text',
                key: 'firstName',
                value: 'John Doe',
                label: 'First Name',
                validation: [
                    {type: 'required'},
                    {type: 'minLength', value: 5, message: 'Please enter a name longer then 5 characters'},
                    {type: 'pattern', value: '^[a-zA-Z ]+$', message: 'Only letters and spaces are allowed'}
                ]
            },
            {
                type: 'password',
                key: 'password',
                label: 'Password',
                validation: [
                    {type: 'required'},
                    {type: 'custom', value: startsWithNumber, message: 'Please dont start with a number'}
                ]
            },
            {
                type: 'dropdown',
                key: 'address',
                label: 'Address',
                value: 'osijek',
                order: 2,
                options: [
                    {value: 'osijek', name: 'Osijek'},
                    {value: 'zagreb', name: 'Zagreb'}
                ]
            },
            {
                type: 'radio',
                key: 'gender',
                label: 'Gender',
                value: 'male',
                classes: {
                    'wrapper': 'some-class-for-the-wrapper',
                    'label': 'label-class',
                    'question': ['q-class-one', 'q-class-two'],
                    'error': ['error-one', 'error-two']
                },
                options: [
                    {value: 'male', name: 'Male'},
                    {value: 'female', name: 'Female'}
                ]
            },
            {
                type: 'checkbox',
                key: 'things',
                label: 'Things You Like',
                values: ['pokemon', 'starWars'],
                options: [
                    {value: 'starWars', name: 'Star Wars'},
                    {value: 'batlefield', name: 'Batlefield'},
                    {value: 'pokemon', name: 'Pokemon'}
                ],
                validation: [
                    {type: 'required'}
                ]
            }
        ]
    };

    onSubmit(event) {
        console.log(event)
    }

    onChanges(event) {
        console.log(event)
    }
}

You can find an example of the setup in the example folder.

System.js

If you are using system.js you also need to declare the library in your system.js config before you can use it.

var map = { 'angular2-easy-forms': 'node_modules/angular2-easy-forms' },
var packages = { 'angular2-easy-forms': {main: 'components.js', defaultExtension: 'js'} }

Questions

Each question can have the following properties:

propertytyperequireddescription
typetext, password, number, dropdown (select), radio or checkboxtrueDefines the type of the question
keystringtrueDefines the key of the control, this is the key of the value that gets emitted onSubmit and onChange
labelstringfalseThe label of the form input
valuestring or array (if question type: 'checkbox' then its an array)falseAn initial value for the question
orderintfalseDefine a specific order for the questions (if one question has an order property to achieve the required effect)
validationobject arrayfalseRead more about validation here

Each question can also have a classes object with the following properties:

propertytyperequireddescription
wrapperstring or string[]falseClass or list of classes to apply to the question wrapper.
labelstring or string[]falseClass or list of classes to apply to the label.
questionstring or string[]falseClass or list of classes to apply to the question element (input, select or div in case of checkbox or radio types).
errorstring or string[]falseClass or list of classes to apply to the error message.

If you define the type of question to be radio, checkbox or dropdown then you need to define an additional property:

propertytyperequireddescription
optionsobject array {value: string, name: string}trueDefine an array of options for the question

Example

{
    type: 'radio',
    key: 'gender',
    label: 'Gender',
    value: 'male',
    classes: {
        'wrapper': 'some-class-for-the-wrapper',
        'label': 'label-class',
        'question': ['q-class-one', 'q-class-two'],
        'error': ['error-one', 'error-two']
    }
    options: [
        {value: 'male', name: 'Male'},
        {value: 'female', name: 'Female'}
    ]
}

Validation

You can optionally set a validation property on any question. The submit button of the form will be disabled if any question is invalid.

The validation property is an object array with the following format:

{
    type: 'required' | 'minLength' | 'maxLength' | 'pattern' | 'match',
    value: string | int | function 
    message: string
}

The message property is the error message and its optional. Don't add the message property if you don't want to display an error message.

Here are the type properties and there associated values

typevaluedescription
'required'noneSet the question to be required
'minLength'intSet the required minimum length of the questions value
'maxLength'intSet the required maximum length of the questions value
'patter'string (regex patter)Set the patter that the questions value needs to satisfy
'custom'functionYou can pass any custom function for validation this way
'match'string (key of the question to match against)This questions value needs to match the assigned questions value

Events

There are two events you can bind to:

  • onSubmit
  • onChange

This is how you bind to them:

<easy-form [easyFormData]="data" (onSubmit)="fuFunction($event)" (onChanges)="barFunction($event)"></easy-form>

onSubmit

The onSubmit event emits when the submit button is pressed. The emitted object contains all of the forms questions with their corresponding values obj[key] = value. If the questions type is 'checkbox' the emitted value is an array of all the checked

OnChange

The onChange event emits when ever a value changes. The following is what gets emitted: {[key]: value}. You can disable a question from triggering the onChange event by setting the emitChanges property to false.

Settings

Along with the list of questions you can add a settings object to the passed data. Here are the possible options:

propertytypedefaultdescription
submitButtonbooleantrueDefine whether to display the submit button or not
submitButtonTextstringSendThe text of the send button
showValidationbooleantrueDefine whether validation errors should be shown or not
singleErrorMessagebooleantrueDefines whether all of the validation errors should be shown or just the last one
errorOnDirtybooleantrueDefine if validation errors should appear only when the input is dirty or right away

You can also provide a classes object to add classes to the form wrapper and the submit wrapper:

classes: {
    // If you want to add a single class pass a string
    // If you want to add multiple classes pass an array os class names
    form: string | string[]
    submit: string | string[]
}

Build

If you want to make a new build:

  • Make your changes to the 'src' folder files
  • Compile each project (source AND example) from Typescript to Javascript:
npm run tsc
  • Move the files from the lib folder to the example node_module folder and launch the example:
gulp serve
0.3.7

7 years ago

0.3.6

7 years ago

0.3.5

7 years ago

0.3.4

7 years ago

0.3.3

7 years ago

0.3.2

7 years ago

0.3.1

7 years ago