A lightweight form builder library for both TypeScript and plain JavaScript
npm install pao-formA lightweight form builder library for both TypeScript and plain JavaScript, inspired by Angular's FormBuilder. This library provides a simple API for creating and managing forms with FormControl, FormGroup, and FormArray.
1. Install the library in your project:
``bash
// via npm
npm install pao-form
// ... or just plug & play import
`
2. Import the library into your TypeScript or JavaScript files:
` javascript
// For TypeScript
import { FormBuilder, FormGroup, FormControl, FormArray } from 'pao-form';
// For Plug & Play JavaScript
import { FormBuilder, FormGroup, FormControl, FormArray } from 'https://cdn.jsdelivr.net/npm/pao-form@latest/dist/pao-form.min.js';
`
` javascript
// Initialize the FormBuilder
const fb = new FormBuilder();
// Create controls with validators
const nameControl = fb.control('John', [Validator.required]);
const ageControl = fb.control(25, [Validator.number]);
// Create a form group
const userFormGroup = fb.group({
name: nameControl,
age: ageControl,
});
// Create an array of controls
const hobbiesArray = fb.array([
fb.control('Reading'),
fb.control('Traveling'),
]);
// It is required to validate the user form group initially
userFormGroup.validateAll()
`
`javascript
// Subscribe to changes in the entire form group
userFormGroup.subscribe(value => {
console.log('Form value changed:', value);
});
// Subscribe to changes in a specific control
nameControl.subscribe(value => {
console.log('Name control changed:', value);
});
`
`javascript
// Set values for the entire form group
userFormGroup.setValue({
name: 'Bob',
age: 28,
});
// Clear values for the entire form group
userFormGroup.clearValue();
`
`javascript
// Create nested form groups
const addressGroup = fb.group({
city: fb.control('New York'),
postalCode: fb.control('10001'),
});
// Add nested group to the main form group
userFormGroup.addControl('address', addressGroup);
`
`javascript`
const Validators = {
required: {
validator: (value) => !!value,
errorMessage: 'This field is required!',
},
number: {
validator: (value) => !isNaN(value),
errorMessage: 'Invalid number!',
}
}
`javascript
// Dynamically add controls to a FormArray
hobbiesArray.controls.push(fb.control('Coding'));
`
`javascript
// Access values in the form group
const formValues = fb.getValue();
console.log('Form values:', formValues);
`
html
`How to run development server?
`
git clone git@github.com:josnin/pao-form.git
cd ~/Documents/pao-form/
npm install
npm run dev
``Need help? Open an issue in: ISSUES