0.0.1 • Published 5 years ago

ngx-model-convert v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

ngx-model-convert

CircleCI npm npm peer dependency version npm License npm bundle size

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

  1. Install via npm or yarn
npm i -S ngx-model-convert
//------------- OR --------------
yarn add ngx-model-convert
  1. 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:

Example 1

Local Development

If you wish to contribute to this repository, below are the steps for local development.

  1. Clone the repository git clone https://github.com/cf91/ngx-model-convert.git
  2. Run npm install to install the dependencies
  3. Run npm build to build both the library and demo app and create a link
  4. Run npm start to build and watch the demo app (opens the app at http://localhost:4200/ automatically)
  5. 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.

0.0.1

5 years ago

0.0.0

5 years ago