angular-formsbuilder-gen v1.0.37
Accelerate Angular Development with Auto Reactive Forms Builder Generator Based On Open API
Unlock enhanced productivity in Angular development with our innovative NPM module! Seamlessly generate form classes directly from OpenAPI specifications, ensuring adherence to Angular best practices. Our solution is tailored for Angular 12 and above, offering compatibility and reliability.
Save valuable time and resources by automating the creation of form group objects. Say goodbye to manual labor and tedious form building processes. Our tool empowers developers with a FormBuilder Helper class, effortlessly generating FormBuilder scripts for each model. Experience streamlined development workflows and expedited project delivery with our intuitive solution.
Optimize your Angular development workflow today and elevate your productivity to new heights!
Installing and running
If you want to install "angular-formsbuilder-gen" globally or just on your project
npm install -g ng-openapi-gen
npm install -g angular-formsbuilder-gen
Then If you want to use it first you need to create configuration file in root of your angular app let's call it 'swagger.json' which should contains following object
{
"$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json",
"input": "https://localhost:44325/swagger/v1/swagger.json",
"output": "./src/app/api",
"ignoreUnusedModels": false,
"modelsPath": "./../api/models",
"formsOutput": "/src/app/forms"
"schemeFile": "E://swagger.json"
}
note this file will be used also for ng-openapi-gen tool Click here to know more about it in section "Configuration file and CLI arguments."
our tool cares only about properties "modelsPath, formsOutput, input"
- Input: url for open-api scheme json file
- schemeFile: local path for scheme json file it's hight order execution if it exist
scheme is loaded from local file instead of url even if url is set
- models: path for generated models ng-openapi-gen
formsOutput: where should our tool generated formsbuilder classes
Generate Services And Models
first we need to generated services and models by using ng-openapi-gen
Execute Following Command:
ng-openapi-gen -c swagger.json
Note: Make sure files are generated in "output" path defined in swagger.json
Generate FormsBuilder Classes
to generate angular you models formsbuilder classes
Execute Following Command:
ng-frmGenerator swagger.json
or you can use
ng-frmGenerator
only because default filename for configuration is "swagger.json"
Example
following example is for simple user information
import { Injectable } from '@angular/core';
import { DatePipe } from '@angular/common';
import { FormControl, FormArray, FormGroup, FormBuilder, AbstractControl } from '@angular/forms';
import { IFormBuilder } from './IFormBuilder';
import { CustomerDto, UserAddressDto } from './../api/models';
import { UserAddressDtoFormBuilder } from './UserAddressDto';
import { oneOfValidator, guidValidator } from './CustomeValidators';
@Injectable({ providedIn: 'root' })
export class CustomerDtoFormBuilder implements IFormBuilder<CustomerDto> {
DatePipe: DatePipe = null as any;
DateFormat: string = 'yyyy-MM-dd';
form: FormGroup = null as any;
constructor(private fb: FormBuilder
, private UserAddressDtoFormBuilderSrvc: UserAddressDtoFormBuilder
) {
this.DatePipe = new DatePipe('en-US');
}
updateCulture(culture: string = 'en-US') {
this.DatePipe = new DatePipe(culture);
}
resetForm() {
this.form.reset();
}
buildForm(model: CustomerDto | null = null) {
this.form = this.fb.group({
userName: [ '' , Validators.compose([ Validators.required, Validators.minLength(1) ]) ],
password: [ '' , Validators.compose([ Validators.required ]) ],
addresses: [ this.UserAddressDtoFormBuilderSrvc.buildForm() ],
});
if (model != null) {
this.form.patchValue({ ...model });
}
return this.form;
}
get userNameCtrl(): FormControl {
return this.form.get('userName') as FormControl;
}
get userNameValueChanges$() {
return this.userNameCtrl?.valueChanges;
}
get passwordCtrl(): FormControl {
return this.form.get('password') as FormControl;
}
get passwordValueChanges$() {
return this.passwordCtrl?.valueChanges;
}
addressesArray(): FormArray {
return this.form.controls['addresses'] as FormArray;
}
addressesControls(): AbstractControl<any, any>[] {
return this.addressesArray().controls;
}
deleteAddressesByIndex(index: number): void {
this.addressesArray().removeAt(index);
}
addNewAddresses(model: UserAddressDtoFormBuilder | null = null): FormGroup<any> {
let frm = this.UserAddressDtoFormBuilderSrvc.buildForm(model);
this.addressesArray().push(frm);
return frm;
}
addNewaddresses(model: UserAddressDto | null = null): FormGroup<any> {
let frm = this.UserAddressDtoFormBuilderSrvc.buildForm(model);
this.addressesArray().push(frm);
return frm;
}
}
---
What Is New?
1.0.37
Add New Forms Helpers that aims to increase performance of developing forms
FormsHelpers.ts This utility file provides convenient methods for enhancing form handling in TypeScript applications.
findName: This function aids in working with interfaces by converting their props into string names compatible with the code.
newId(): Generates a new unique identifier using Guid, ensuring each ID is distinct.
emptyId: Returns the empty Guid '00000000-0000-0000-0000-000000000000', useful for initializing identifiers.
removeControls: Simplifies the process of removing controls from a form group, reducing potential issues such as compiler errors that may arise from changing field names. Usage example:
removeControls<userModel>([
a => a.age,
a => a.address
], this.frm);
- markAsRequired: Extends the functionality of removeControls by adding required validation to form controls using shorthand syntax. Example:
markAsRequired<LoginModel>([
a => a.password,
a => a.userName
], this.frm);
- markAllAsRequired: Applies required validation to all form controls within a form group. Example:
markAllAsRequired(this.frm)
- markAllAsRequiredExcept: Adds required validation to all form controls except those specified, enhancing control over form validation. Example:
CustomeValidator.ts:
New Validator Add CompareFields: used in cases that both controls values must be qual like password confirmation
markAllAsRequiredExcept<PasswordChangeModel>(this.frm,[
a => a.passwordChangeToken,
a => a.userId
]);
- setRequired: marks control as required by it's name ( note: name given as string, not preferred )
1.0.36
in this version I've made a refactor in core behaviour of generating the files in order to support basic validations defined in swagger.json document.
fix some issues which causes missing props in some models.
fix issue of build related to custome validator guidValidator
Generated File Content
- Fields: Contains variables used in file
- Constructor: Conatins default configuration
- Methods: -buildForm Method: Responsable for creating and updating generated form data. -Arrays and Navigation methods
- Properties: -Property Control: returns instance of control as FormControl -Property ValueChange: returns observable of Control Value Changes
Features
- Generate Angular FormsBuilder Class for All Models
- You Can Extend Class Functionality by inheritance In Sperate Service File
- Write Controls Getters for Better IntelliSense
- Give you a high productivity in implementing different forms because I you will save time of writing different reactive forms 'formbuilder object' and focuse on writing required logic of form.
Notes
Github repository moved to bitbucket
2 months ago
2 months ago
3 months ago
3 months ago
4 months ago
9 months ago
8 months ago
8 months ago
9 months ago
9 months ago
6 months ago
9 months ago
8 months ago
8 months ago
9 months ago
9 months ago
9 months ago
10 months ago
10 months ago
10 months ago