Angular Create Custom Pipe for Replace Null Values Example

By Hardik Savani October 20, 2023 Category : Angular

Hi,

In this tutorial, i will show you angular pipe for null values. you can see angular pipe replace null value. we will help you to give example of check null value and replace angular pipe. if you want to see example of angular null value pipe then you are a right place. follow bellow step for angular pipe for null.

you can easily create custom pipe for replace null value in angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 version.

here, you have to follow few step to create simple example of custom pipe for null values. let's see one by one.

Step 1: Create New App

If you are doing example from scratch then You can easily create your angular app using bellow command:

ng new app-material

Step 2: Create Custom Pipe

We need to run following command to creating pipe in angular application.

ng generate pipe null-with-default

Now we need to write some logic on our custom pipe ts file. so let's write logic as i written for demo now.

app/null-with-default.pipe.ts

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

@Pipe({

name: 'nullWithDefault'

})

export class NullWithDefaultPipe implements PipeTransform {

transform(value: any, defaultText: string = 'N/A'): any {

if (typeof value === 'undefined' || value === null) {

return defaultText;

}

return value;

}

}

now it should be import in module.ts file as bellow:

app/app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { NullWithDefaultPipe } from './null-with-default.pipe';

@NgModule({

imports: [ BrowserModule, FormsModule ],

declarations: [ AppComponent, NullWithDefaultPipe ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

Step 3: Use Custom Pipe

Now we need to create one variables and use it, let's add code as like bellow:

app/app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular ' + VERSION.major;

title = 'ItSolutionStuff.com Post';

description = null;

user_id = null;

}

Ok, now we can use 'nullWithDefault' custom pipe in html file, so let's write it.

app/app.component.html

<p>Title: {{ title | nullWithDefault }}</p>

<p>Description: {{ description | nullWithDefault }}</p>

<p>user_id: {{ user_id | nullWithDefault }}</p>

Output:

Title: ItSolutionStuff.com Post

Description: N/A

user_id: N/A

I hope it can help you...

Tags :
Shares