angularangular-pipepipes-filters

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


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


Solution

  • 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>