Custom Angular title case pipe built on top of Angular's titleCase pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- USAGE --> | |
<!-- Transoforming strings --> | |
<div class="users"> | |
<div class="users__user" *ngFor="let user of users"> | |
{{user.name | appTitleCase}} | |
</div> | |
</div> | |
<!-- Transforming Arrays --> | |
<!-- Suited for cases where we have to pass an array into a component whose template we don't have access to --> | |
<div class="form"> | |
<input class="form__members" typeahead [typeaheadData]="$users | async | appTitleCase : 'full_name'"> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
import { TitleCasePipe as AngularTitleCasePipe } from '@angular/common'; | |
@Pipe({ | |
name: 'appTitleCase' | |
}) | |
export class TitleCasePipe implements PipeTransform { | |
angularTitleCase = new AngularTitleCasePipe(); | |
transform(value: any, ...args: any[]): any { | |
const property = args[0]; | |
const isValidProperty = property && typeof property === 'string'; | |
if (typeof value === 'string') { | |
// if the value we have to transform is a simple string | |
return this.angularTitleCase.transform(value); | |
} else if (Array.isArray(value)) { | |
// if the value we have to transform is an array | |
return value.map((item) => { | |
// if the current item in the array is a simple string, we transform it | |
if (typeof item === 'string') { | |
return this.angularTitleCase.transform(item); | |
} else if (isValidProperty && item[property]) { | |
// if the item in the array is an object and we have the property in the object, we transform item | |
item[property] = this.angularTitleCase.transform(item[property]); | |
} | |
return item; | |
}); | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment