ERROR TypeError: Cannot read property 'split' of null in angular custom pipe

2.9k Views Asked by At

I am getting this error ERROR TypeError: Cannot read property 'split' of null error while using this angular pipe and here is the code.

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

@Pipe({
  name: 'fullDate'
})
export class DatePipe implements PipeTransform {

  transform(value:any ) {
    const dateArray = value.split('-');
    const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  
    return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
  }

}

{{ lorem?.lorem_date | fullDate }}

enter image description here

3

There are 3 best solutions below

0
On BEST ANSWER

Add a null check in the pipe:

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

@Pipe({
  name: 'fullDate'
})
export class DatePipe implements PipeTransform {
  transform(value: any) {
    if (value) {
      const dateArray = value.split('-');
      const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
      const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

      return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
    }
    return value;
  }
}

OR

Place the content in an *ngIf:

<p *ngIf="lorem">{{ lorem.lorem_date | fullDate }}</p>
1
On

The error means that you are splitting a value that is null, so you can just add a check.

Try like this:

transform(value:any ) {
   if(value){ 
        const dateArray = value.split('-');
        const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
    }
  }
0
On

What basically happens in your code is when its is running on the first time value varible doesnt have any value assigned. since because of that it return and error saying Cannot read property 'split' of null Validating the value inside the pipe for having a value will do. Please find the sample code below:

 

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

    @Pipe({
      name: 'fullDate'
    })
    export class DatePipe implements PipeTransform {

      transform(value:any ) {
        if(value){
        const dateArray = value.split('-');
        const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      
        return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
      }


    }