Skip to content

Angular library which provides a powerful base directive (BaseCvaImplementationDirective<T>) making it easy to create custom form controls with built-in validation support. Controls created by extending the directive supports both Template driven and Reactive forms.

License

Notifications You must be signed in to change notification settings

kapilkumar0037/ngx-custom-controls

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NGX Custom Controls

Angular library which provides a powerful base directive (BaseCvaImplementationDirective<T>) that implements both ControlValueAccessor and Validator interfaces, making it easy to create custom form controls with built-in validation support. Every custom control implemented by extending the base directive will support both template-driven and reactive forms. Library also provides basic control components created using base directive and bootstrap css.

If you find this library helpful, please consider giving it a ⭐ on GitHub!

Why Use This Library?

  • Simplified Custom Control Creation: Create your own form controls by extending the base directive, eliminating the need to implement complex form control interfaces manually
  • Type-Safe: Fully generic implementation allows you to specify the type of value your control will handle
  • Framework Agnostic: Works seamlessly with both template-driven and reactive forms
  • Validation Made Easy: We can use
  • DRY Principle: The base directive handles all the boilerplate code for form integration

Features

  • 🎯 Framework agnostic form controls
  • βœ… Built-in validation support with custom messages
  • πŸ”„ Two-way binding support
  • 🎨 Customizable styling
  • πŸ“¦ Lightweight and tree-shakeable
  • πŸ›‘οΈ Written in TypeScript with strict type checking
  • πŸ”§ Extensible base directive for custom controls
  • πŸ“ Built-in form state tracking (touched, dirty, etc.)

Installation

npm install ngx-custom-controls

Basic Usage

Import the desired components in your module or standalone component:

import { CustomInputComponent } from 'ngx-custom-controls';

@Component({
  // ...
  imports: [CustomInputComponent]
})

Template Usage Example

@Component({
  template: `
    <ngcc-custom-input
      name="email"
      controlId="emailField"
      [(ngModel)]="email"
      [validators]="emailValidators">
    </ngcc-custom-input>
  `
})
export class ExampleComponent {
  email = '';
  
  emailValidators = [
    {
      validator: Validators.required,
      message: 'Email is required'
    },
    {
      validator: Validators.email,
      message: 'Please enter a valid email'
    }
  ];
}

We just need to write all applicable validators and provide it to the control and everything else will be handled by the directive.

Creating Custom Controls

You can create your own form controls by extending the BaseCvaImplementationDirective:

import { Component, input } from '@angular/core';
import { NgClass } from '@angular/common';
import { cvaProviders } from '../../shared/providers/cva-providers';
import { BaseCvaImplementationDirective } from '../../shared/directives/base-cva-implementation.directive';
import { ValidationMessagesComponent } from '../../shared/components/validation-messages/validation-messages.component';

@Component({
  selector: 'ngcc-custom-input',
  imports: [NgClass, ValidationMessagesComponent],
  standalone: true,
  templateUrl: './custom-input.component.html',
  providers: [...cvaProviders(CustomInputComponent)]  
})
export class CustomInputComponent extends BaseCvaImplementationDirective<string> {
  styleClass = input('form-control');
  placeholder = input('Enter');
  type = input('text');
  ngOnInit() {
    this.value = '';
  }
}

In most cases you need not to write any code in your control it's only when you need to override something.

Usage in parent component

It's time to use your component now

Reactive form example

  <form [formGroup]="ageForm">
    <ngcc-custom-input controlId="age" placeholder="21" formControlName="age" [validators]="ageValidators"
      [type]="'number'">
      <label for="age">Age</label>
    </ngcc-custom-input>
  </form>
ageForm = new FormGroup({
    age: new FormControl(22)
  });
  ageValidators = [
    {
      validator: Validators.required,
      message: 'Age is required'
    },
    {
      validator: Validators.min(18),
      message: 'Must be at least 18 years old'
    },
    {
      validator: Validators.max(100),
      message: 'Must be less than 100 years old'
    }
  ];

You se we have just added applicable validators which can also be shared using shared validator class.

This example demonstrates:

  • Creating a custom input component supporting dynamic "type", placeholder and css class
  • Number type input to create age input box.
  • Integration with reactive forms using formControlName
  • Custom value parsing
  • Bootstrap validation styling
  • Multiple validators with custom messages

Template driven form example

  <ngcc-custom-input controlId="tage" placeholder="22" [(ngModel)]="age" [validators]="ageValidators" [type]="'number'">
    <label for="tage">Age</label>
  </ngcc-custom-input>
age:number;
//Same validators used for reactive form control
ageValidators = [
    {
      validator: Validators.required,
      message: 'Age is required'
    },
    {
      validator: Validators.min(18),
      message: 'Must be at least 18 years old'
    },
    {
      validator: Validators.max(100),
      message: 'Must be less than 100 years old'
    }
  ];

Base Directive Properties

The BaseCvaImplementationDirective provides:

Inputs

  • validators: Array of ValidatorWithMessage[]
  • name: Control name
  • controlId: Unique identifier

Properties

  • value: Current control value
  • validationErrors: Current validation errors
  • errorMessages: Array of error messages
  • isTouched: Touch state
  • isDirty: Dirty state

Methods

  • onInputChange(value: T): Handle value changes
  • markAsTouched(): Mark control as touched
  • runValidators(): Execute validation

Validation

Define validators with custom messages:

const validators = [
  {
    validator: Validators.required,
    message: 'This field is required'
  },
  {
    validator: Validators.minLength(3),
    message: 'Minimum length is 3 characters'
  }
];

Components included in library created with Bootstrap css

  • Custom input component
  • Custom select component
  • Custom range component
  • Custom Date picker components
  • Custom Checkbox
  • Custom Radio

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Angular library which provides a powerful base directive (BaseCvaImplementationDirective<T>) making it easy to create custom form controls with built-in validation support. Controls created by extending the directive supports both Template driven and Reactive forms.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published