JSPM

  • Created
  • Published
  • Downloads 16
  • Score
    100M100P100Q64998F

Package Exports

  • goteti-forms

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (goteti-forms) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Goteti Forms

Author: Narasimha Goteti

"GotetiForms" library is for the Angular (2+) project development.

Bootstrap 3 (or later) version is required for this Package for existing styling.

NOTE: Version 2.1.1 is not compatible with version 1. Please follow the version migration details below.

Version 1 to Version 2 migration:

  1. type = 'component' support has been added to GotetiInputFieldComponent.
  2. Add the custom input components to the GotetiFormsService in ngModule or Component level.
  3. GtMapBuilder is updated to support single field form-control .
  4. type='fnumber' support has been removed , please create your own component and add it type='component', component:''.

Integration Steps:

Install package in the root folder using the command,

npm i goteti-forms

Add the module to the NgModule of main application.

import { GotetiFormsModule, GotetiFormsService } from 'goteti-forms';
@NgModule({
declarations: [
    AppComponent
],
imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    GotetiFormsModule  // <--- Add the Module 
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
    constructor (private GFS: GotetiFormsService){
        GFS.addComponent('rating', <Your Custom Input Component>);
    }
}

Module contains the following:

import {
    AtbrDirective, DebounceInputDirective, FilterPipe, GotetiAutoSelectComponent, GotetiFormsComponent, GotetiFormsModule, GotetiFormsService, GotetiInputFieldComponent, GotetiRecursiveFormControlComponent, GtMapBuilder, HighlightSearch, IpolatePipe, ListenerDirective, PermissionDirective, PermissionDirectiveDisable, SetFocusDirective, getValidatorsList, generateFormControl, sampleReactiveFormData
} from 'goteti-forms';

Details of all the Components / Pipes / Directives / Utils.

1) Component : GotetiInputFieldComponent

Example:

// Supports both Template driven and Reactive forms

//app.component.html 
    
    <goteti-input-field 
        [config]="configuration" 
        [listen]="{input: onInputValue, change: onChangeValue}"
        [args]="'Put the customised arguments here'"
        [(ngModel)]="title" required>
    </goteti-input-field>

//app.component.ts
ngOnInit(){
    this.configuration =  {
            "label": "Name",
            "type": "auto-select",
            "template": null,  
            "class": "form-control",
            "multiple": true,
            "listValue": "capital",
            "disable": false,
            "hide": false,
            "itpolate": "{name}'s last Name is {lastname} !",
            "list":[{"name":"Narasimha","lastname":"Goteti"},
                    {"name":"Sai","lastname": "Vutukuru"}],
            "atbr": {
              "placeholder": "It's upto you! "
            },
            "errors":{
                "required":{
                    "msg": "Name is required",
                    "class": "text-warning"
                }
            },
            "validations": [{
              "key": "minLength",
              "value": 5
            },{
              "key": "required",
              "value": 5
            }]
          };        

}

onInputValue(event, args){
    console.log(event) // event, 'Put the customised arguments here' 
}

onChangeValue(event, args){
    console.log(event) //// event, 'Put the customised arguments here' 
}

Properties of [config]:

Properties Description Values Supported / Example
label Label for Input field String , null
class Class for the Input field ex: 'form-control classname'
disable If it is 'true', input will be in disable state , Even modifing the attributes from developer tools (inspect elements ) will not work i.e still input field will be disable state true / false
hide It is NOT CSS based it is *ngIf based. true / false
value Value of input
type All basic input types additional to Library input types i.e (auto-select, fnumber), This DO NOT support 'select' type. auto-select, template, component, textarea, text, number and (all input types)
template TemplateRef. ex: template: 'calender' <ng-template #calender> custom component </\ng-teplate>
multiple 'true' for multi-select , 'false' for single select. multiple true works only for type='auto-select'. true / false
listValue type="auto-select" selected value should be property or whole selected object of array iteration Property key or null
itpolate type="auto-select", It is string with {key} ,format of displaying data in dropdown. 'My name is {name} and last name is {lastname} !'
list type="auto-select", Array of Objects or Array of non-objects for dropdown Array of objects, Array of non-objects
atbr Attributes for input field ex: {step: 10}
random Random number has to be updated when ever atbr value is updated inorder to update the Input field's attribute. Math.random()
errors Error messages which displays in input field
validations Validation object value for Reactive form

Supported 'type' values

HTML types: text , number , range ... etc

Library supported types : auto-select, template, component .

type:"template"

If type:"template" then template: "templateName" and [templates]="{templateName: templateName}" like below

    this.configuration = {
        "label": "Birthdate",
        "type": "template",
        "template": "calender"  
    }

    // HTML implementation.
    <goteti-input-field 
        [config]="configuration" 
        [listen]="{change: onChangeValue}"
        [templates]="{'calender': calender}"
        [(ngModel)]="bod" required>
    </goteti-input-field>

    <ng-template #calender let-setvalue="setValue" let-value="value" let-config="config"> 
        <gt-calender [value]="value" (valueChange)="setvalue($event)"></gt-calender> 
    </ng-template>

Properties of [listen]:

listen attribute accept the object with key and value, where key is valid input events like 'input','change','keydown'... etc , value is the function which needs to handle in '.ts' file.

Properties of [args]:

args=Arguments of listen events, [listen] attribute is mandatory for this , so that arguments will be passed to listen events like 'input, change, keydown,keypress'.

'args' can be String, Array, Object.

type:'component'

If type:"component" follow the below structure and Make sure you add the custome input component to the GotetiFormsService.

// app.module.ts
export class AppModule {
    constructor (private GFS: GotetiFormsService){
        GFS.addComponent('rating', RatingComponent);
    } 
}
/* RatingComponent is project level custom input component , i.e not the part of GotetiForms. Put your custom input component in place of RatingComponent */ 

//app.component.ts
this.configuration = {
    "label": "Rate the Feedback!",
    "type": "component",
    "component": "rating",
    "errors":{
        "required":{
            "msg": "Feedback is required",
            "class": "text-danger"
        }
    },
    "validations":[{
        key:'required',
        value: null
    }]
}

onChangeValue(ev){
     console.log( arguments)
}

// HTML implementation.
<goteti-input-field 
    [config]="configuration" 
    [listen]="{change: onChangeValue}"
    [(ngModel)]="ratingValue">
</goteti-input-field>

Custom Input Component

export class RatingInputComponent implements OnInit, OnChanges{
    @Input() config;
    @Input() listen;
    @Input() args;
    @Input() setvalue;
    @Input() value;
    @Input() setvalue; // it is function to update the Value
    @Input() value; // Updated value
    rate(rating: number) {
        let val = this.value == rating ? 0 : rating;
        this.value = val;
        this.setvalue(val);
    }

    ngOnInit(){
        
    }

    ngOnChanges(sc: SimpleChanges){
        
    }

    propschanged(props, key){ 
        /* This funtion is  fired when value is changed in parent level i.e alternative to ngOnChanges */
        this[key] = props;
        this.rate(props)
    }

}

'GotetiFormsService' methods:

getComponent(key)
getAllComponents()
addComponent(name, component)
removeComponent(key)
setComponents(componentlist)

2. Pipe: IpolatePipe

Example:

this.value = {
    name: 'India'
}


<span> {{ value | itpolate: 'Country name is {name}'  }} </span>

3. Directive: AtbrDirective , depends on [random]

Example:

this.attributes = {
    step: 3,
    placeholder: 'This is the place holder'
};

this.random = Math.random();


<input 
    [atbr]="attributes"
    [random]="random"
/>

4. Directive: [hide] , [disable]

this.rules = {
    hide: true,
    disable: true
}

<input 
    *hide="rules.hide"
    [disable]="rules.disable"
/>

[disable]="true" , Disables the element even you change the properties in developer tools i.e inspect elements.

5. Directive : [listener] (ListenerDirective)

onInputChange(event){
    // some functionality
}

onKeypress(event){
    // some functionality
}

<input 
    [listener]="{input: onInputChange, keypress: onKeypress}"
    [args]="['Parameter 1', 'Parameter 2']"
/>

6. Recursive Reactive FORM

// .ts implementation

import  { GtMapBuilder, sampleReactiveFormData } from 'goteti-forms';


fields = sampleReactiveFormData;    
formData;
_this = this;

ngOnInit(){
    this.formData =  GtMapBuilder(sampleReactiveFormData, {
        ageRange: this.ageRangeValidator, 
        addressList: this.addressList
    });
}

listenActions(type, index = ''){
    switch(type){
        case 'phones': {
                this.formData.get('phones').push(generateFormControl(sampleReactiveFormData.phones))
            break;
        }
        case 'address': {
                this.formData.get('address').push(GtMapBuilder(sampleReactiveFormData.address.props))
            break;
        }
        case 'address.delete':{
                this.formData.get('address').removeAt(index);
            break;
        }
    }
}

ageRangeValidator(list): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (control.value !== undefined && (isNaN(control.value) || control.value < list[0] || control.value > list[1])) {
            return { 'ageRange': true };
        }
        return null;
    };
}

addressList(len): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (control.value && control.value.length != len) {
            return { 'addressList': true };
        }
        return null;
    };
}



// html implementation
<goteti-recursive-form-control 
    [control]="formData"
    [fields]="fields"
    [listenActions]="listenActions.bind(_this)">
</goteti-recursive-form-control>     

Properties of [fields]:

Properties Description Values Supported / Example
isObject true / false , Implementation of Formbuilder.Object, If isObject is true , "props" is mandatory. GtMapBuilder(
{address: { isObject: true, class:'col-md-10', props:{ city: {class:'col-md-3', config: {type:'text'} }}}
, VALIDATIONS_OBJECT)
isArray true/false , Implementation of Formbuilder.Array. GtMapBuilder(
{phones: {isArray: true, isSingle:true, class:'col-md-4', config: {type:'number'}}}
, VALIDATIONS_OBJECT)
isSingle If isArray is true, then isSingle is true for Array of non-objects(i.e Array of FormControl) , isSingle is false for Array of objects (i.e Array of FormObjects), if isSingle is false , props is mandatory. GtMapBuilder(
{Subjects:{isArray: true, isSingle: false, props: { maths:{config: {type: 'number'}}, physics: {config: {type: 'number'}}}}}
, VALIDATIONS_OBJECT)
props It is object(with config like goteti-input-field config properties) , if isArray is true and isSingle is false Same like above
config It is configuration like goteti-input-field config. config property is mandatory if isArray is true and isSingle is true Same like above
actions Array of objects with buttons configurations [{label:'Button name',key:'unique key of button', class:'classes of button'}]
validations Array of validations objects, if array or object needs validations. [{"key": "addressList","value": 2}]
errors key and value Object for validation messages.
{"errors":{  "addressList":{"msg": "Mininum 2 Addresses are required","class": "text-danger"},"ageRange": {"msg": "Age should be between 10 and 20","class": "text-info"}}}

[control]: Form builder object.

[listenActions]: Function which handles the actions events.

GtMapBuilder: It is Form builder, first parameter is the 'fields' data object, second parameter is the all the validators object supported by application. If you are using any custome validation in validations property in config , those validator functions has to be provided as the second paramenter to this function.

Using 'goteti-recursive-form-control' component will render the all the elements dynamically as shown in below image.

Goteti Recursive Reactive form

For explanation please find the properties of 'sampleReactiveFormData' i.e console.log(sampleReactiveFormData). This document update is still in-progress to list out the all the config properties of 'goteti-recursive-form-control'.

Licence

Open Source - Free to use.