ngx-model-convert v0.0.1
ngx-model-convert
Because I'm tired of copying this stuff between projects. https://www.npmjs.com/package/ngx-model-convert
About
Sometimes the value a user enters is not in the same format that your application works with. A common example is a percentage. People like to enter '10' while your code may work with '0.1'. So where do you do this conversion?
This module provides a generic and convenient way to convert between user input and ngModel format. It provides percentage conversion out of the box.
Getting Started
- Install via npm or yarn
npm i -S ngx-model-convert
//------------- OR --------------
yarn add ngx-model-convert
- Import
NgxModelConvertModule
in your application
import { NgxModelConvertModule } from 'ngx-model-convert';
@NgModule({
...
imports: [NgxModelConvertModule],
...
})
export class AppModule { }
Usage
Implement the ModelConverter<T>
interface for custom converters:
export interface ModelConverter<T> {
output: (v: T) => string; // Convert from ngModel -> user input format
input: (v: string) => T; // Convert from user input -> ngModel format
}
Then use ngxModelConvert
on your inputs:
<input type="text" [ngxModelConvert]="myConverter" [(ngModel)]="myModel" />
E.g. Percentages
Note This is already available via import { PERCENT_CONVERTER } from 'ngx-model-convert';
Implement the ModelConverter<T>
interface for percentage conversion:
export const PERCENT_CONVERTER: ModelConverter<number> = {
output: v => (isNumeric(v) ? String(v * 100) : null),
input: v => (isNumeric(v) ? Number(v) / 100 : null)
};
Then use on your input:
<input type="text" [ngxModelConvert]="PERCENT_CONVERTER" [(ngModel)]="myModel" />
This is the result:
Local Development
If you wish to contribute to this repository, below are the steps for local development.
- Clone the repository
git clone https://github.com/cf91/ngx-model-convert.git
- Run
npm install
to install the dependencies - Run
npm build
to build both the library and demo app and create a link - Run
npm start
to build and watch the demo app (opens the app athttp://localhost:4200/
automatically) - Run
npm watch:lib
to build and watch the library
Build
Run npm run build
to build the library and demo app together. The build artifacts will be stored in the dist/
directory.
This step is used by CircleCI to build both library and demo app. After a succesful build, a new semantic version of library is published to npm.
Tests
Run npm run test:lib
or npm run test:app
to execute the unit tests via Karma.