Ionic – costum pipes

Table of Contents

Source

Starter-Code

Creating a pipe

				
					// ./pipes/weakness.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'weakness'
})

export class WeaknessPipe implements PipeTransform {
  transform(value: any): string {
    if (value == null) {
      return '1x';
    } else if (value == 0.5) {
      return '1/2x';
    } else if (value == 0.25) {
      return '1/4x';
    } else {
      return value + 'x';
    }
  }
}
				
			

A module for the import in to your page.

				
					// ./pipes/pipes.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { WeaknessPipe } from './weakness.pipe';


@NgModule({
  imports: [CommonModule],
  declarations: [WeaknessPipe],
  exports: [WeaknessPipe]
})
export class PipesModule { }

				
			

Import the pipe module to your page.

				
					// ./pages/yourpage.module.ts

import { PipesModule } from '../../pipes/pipes.module';

@NgModule({
  imports: [
    CommonModule,
    PipesModule
  ],
})
export class YourPagePageModule {}
				
			

Use it like this in your html.

				
					// ./pages/YourPage.page.html

{{your.value | weakness}}
				
			

Or in your typescript. import and declare in the constructor.

				
					// ./pages/YourPage.page.ts

import {WeaknessPipe} from '../../pipes/weakness.pipe';

constructor(public weakness: WeaknessPipe) {}
				
			

If you want use your pipe only in .html. you don’t have to import to .ts.

If you want to add multiple arguments

				
					// your.html

value="{{c.value | stats :  c.key}}"
				
			

Thats it have fun