Skip to content

Instantly share code, notes, and snippets.

@joeskeen
Last active March 27, 2019 19:07
Show Gist options
  • Save joeskeen/2eff967a4d4860b226cf31d0b95640fa to your computer and use it in GitHub Desktop.
Save joeskeen/2eff967a4d4860b226cf31d0b95640fa to your computer and use it in GitHub Desktop.
Angular pipe for changing to any case (esp. not those included in @angular/common)
import { PipeTransform, Pipe } from '@angular/core';
import * as changeCase from 'change-case';
type TransformFn = (val: string) => string;
@Pipe({ name: 'joeCase', pure: true })
export class CasePipe implements PipeTransform {
/**
* changes the case of a value
* @param value the value to change the case of
* @param transform the name of the change case function to use.
* See https://www.npmjs.com/package/change-case for valid function names.
*/
transform(value: any, transform: string) {
if (value == null || value === undefined) {
return '';
}
const strValue: string = value.toString();
const transformFn: TransformFn = changeCase[transform];
if (!transformFn) {
throw new Error(
`Cannot perform unknown transform '${transform}' to value '${value}'.
For a list of supported transforms, see https://www.npmjs.com/package/change-case`
);
}
return transformFn(strValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment