balaji
balaji

Reputation: 27

Trying to reproduce the same predefined uppercase function using custom pipe ---> Getting this error in console

HTML template example using the pipe:

<input type="text" [(ngModel)]="titleCasing" (keyup.enter)="titleCasingFun()" />

<span>{{ titleCasing | titleCasingtransform }}</span>

Custom Pipe implementation:

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

@Pipe({ name: 'titleCasingtransform' })
export class TitlecasingPipe implements PipeTransform {
  transform(titleCasing: string) {
    return titleCasing.toUpperCase();
  }
}

Getting Below Error

core.js:6456 ERROR TypeError: Cannot read property 'toUpperCase' of undefined

Upvotes: 1

Views: 183

Answers (2)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9903

The error clearly said that titleCasing is undefined. Very simple way is to use Optional chaining (?.) that introduced in typescript-3-7:

export class TitlecasingPipe implements PipeTransform {
  transform(titleCasing: string) {
    return titleCasing?.toUpperCase();
  }
}

Upvotes: 1

IAfanasov
IAfanasov

Reputation: 4993

I see only one toUpperCase call. That means titleCasing is undefined. To deal with it one can do the check for undefined. A possible solution would be:

transform(titleCasing: string) {
  return titleCasing && titleCasing.toUpperCase();
}

While in general, one can not be sure that pipe would receive a string as an argument for the transform pipe. For production-ready reusable pipe, it would be wise to handle such cases. A possible solution would be to throw an exception if the argument is not a string.

transform(titleCasing: any) {
  if (typeof value !== 'string') {
    throw invalidPipeArgumentError(LowerCasePipe, value);
  }
  return titleCasing && titleCasing.toUpperCase();
}

or convert argument to a string:

transform(titleCasing: any) {
  return titleCasing && `${titleCasing}`.toUpperCase();
}

Which might handle false unexpectedly and some other edge cases. It might not be worth the coding to handle edge cases for your project. So, it's up to you to decide on it.

Upvotes: 1

Related Questions