Creating and Testing an Angular Library for Form Validation
As an Angular developer, creating reusable components and libraries can significantly streamline your development process. One common task in many projects is form validation. Instead of writing validation logic for every project, you can create an npm package for form validation and make it publicly available. In this blog post, I'll walk you through the process of creating an Angular library for form validation, publishing it to npm, and testing it in a sample project.
1. Setting Up Your Angular Library
First, let's set up the library:
Create an Angular Library
Run the following commands to create a new Angular library:
ng new angular-validation-lib --create-application=false
cd angular-validation-lib
ng generate library validation-lib
Develop Your Library
Add your form validation logic inside the library. Create components, services, or directives as needed.
2. Building Your Library
Build the Library
Run the following command to build your library:
ng build validation-lib
Package the Library
Navigate to the dist/validation-lib directory. Ensure you have a proper package.json file in place:
{ "name": "@abhinaya2022/validation-lib", "version": "1.0.0", "description": "A library for form validation in Angular", "author": "Your Name", "license": "MIT", "main": "bundles/validation-lib.umd.js", "module": "fesm5/validation-lib.js", "es2015": "fesm2015/validation-lib.js", "typings": "validation-lib.d.ts", "peerDependencies": { "@angular/common": "^12.0.0", "@angular/core": "^12.0.0" } }
3. Publishing to npm
Create an npm Account
If you don't have an npm account, create one at npmjs.com/signup. Verify your email and log in to npm using:
npm login
Publish Your Library
Publish your library with the following command:
npm publish --access public
If you encounter a conflict with the package name, use a scoped package name:
npm publish --access public
4. Documentation
Ensure your README.md file is comprehensive. Include the following sections:
Package Name and Description
# @abhinaya2022/validation-lib
A library for form validation in Angular.
Installation Instructions
## Installation
To install this library, run:
npm install @abhinaya2022/validation-lib
### Usage Guide
## Usage
### Import the Module
In your `app.module.ts`, import the library module:
import { ValidationLibModule } from '@abhinaya2022/validation-lib';
@NgModule({
imports: [
// other imports...
ValidationLibModule
]
})
export class AppModule { }
Using Validators
Here's an example of how to use the validators provided by the library:
typescriptimport { FormBuilder, FormGroup, Validators } from '@angular/forms';import { CustomValidators } from '@abhinaya2022/validation-lib';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', [Validators.required, CustomValidators.email]],
password: ['', [Validators.required, CustomValidators.password]]
});
}
onSubmit() {
if (this.form.valid) {
// handle form submission
}
}
}
### API Reference
```markdown
## API Reference
### CustomValidators
- `CustomValidators.email`: Validates email addresses.
- `CustomValidators.password`: Validates passwords with specific criteria.
### Other Components
Document other components, services, or directives provided by the library.
Contribution Guidelines
markdown## Contributing
Contributions are welcome! Please submit a pull request or open an issue to discuss potential changes.
### Steps to Contribute
1. Fork the repository.
2. Create a new branch: `git checkout -b feature/your-feature`
3. Commit your changes: `git commit -m 'Add some feature'`
4. Push to the branch: `git push origin feature/your-feature`
5. Open a pull request.
License
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
5. Testing Your Library
Create a New Angular Project
Create a new Angular project to test your library:
ng new angular-validation-lib-democd angular-validation-lib-demo
Install Your Library
Install your library in the new project:
npm install @abhinaya2022/validation-lib
Import and Use Your Library
Update app.module.ts to import the library module:
typescriptimport { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { ValidationLibModule } from '@abhinaya2022/validation-lib';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
ReactiveFormsModule,
ValidationLibModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Generate a new component to test the library:
ng generate component TestComponent
Update test.component.ts to use your validation library:
typescriptimport { Component } from '@angular/core';import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomValidators } from '@abhinaya2022/validation-lib';
@Component({
selector: 'app-test',
templateUrl: './test.component.html'
})
export class TestComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', [Validators.required, CustomValidators.email]],
password: ['', [Validators.required, CustomValidators.password]]
});
}
onSubmit() {
if (this.form.valid) {
console.log('Form Submitted!', this.form.value);
} else {
console.log('Form Invalid');
}
}
}
Update test.component.html to include a form:
html<form [formGroup]="form" (ngSubmit)="onSubmit()">
<ngx-input [label]="'email'" [type]="'text'" [isSubmitted]="false" formControlName="email"> </ngx-input>
<button type="submit" (click)="isSubmitted = true">Submit</button>
</form>
Add the test component to app.component.html:
Run the Application
Run the application to test your library in action:
ng serve
Test Various Scenarios
- Test form validation by entering valid and invalid data.
- Verify that validation messages are displayed correctly.
- Check that the form submission logic works as expected.
Debugging and Iteration
If issues are found, fix them in your library, rebuild it, and reinstall it in the demo project. Use npm link for faster iterations during development.
Using npm link
For development, you can link your library for faster testing:
Link Your Library
In your library project directory:
npm linkLink the Library in Your Demo Project
In your demo project directory:
npm link @abhinaya2022/validation-libThis allows you to make changes to your library and see them reflected in the demo project immediately without having to publish and reinstall the library repeatedly.
By following these steps, you can create, publish, and test your Angular validation library, ensuring it works correctly when integrated into other projects. Happy coding!
for More Information click referance article
Comments
Post a Comment