Created
October 25, 2021 16:28
-
-
Save krohne/a55096509af7621a36e2ce09b90fa385 to your computer and use it in GitHub Desktop.
Angular pipe to trim and contatenate strings with space between. Mostly for formatting names, which may include null/undefined values, or leading/trailing spaces
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
// app.module.ts | |
import { MultiStringPipe } from './MultiString.pipe'; | |
@NgModule({ | |
declarations: [ | |
//... | |
MultiStringPipe, | |
], | |
}) | |
export class AppModule {} |
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
// MultiString.pipe.ts | |
import { | |
Pipe, | |
PipeTransform | |
} from '@angular/core'; | |
@Pipe({ name: 'multiString' }) | |
export class MultiStringPipe implements PipeTransform { | |
function transform(...values: string[]): string { | |
return values | |
.reduce( (prev, curr) => | |
`${prev} ${(curr ?? '').trim()}`.trim(), | |
''); | |
} | |
} |
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
// name-format.component.ts | |
import { Component } from '@angular/core'; | |
@Component({ | |
selector: 'name-format', | |
template: ` | |
<h2>Name Format</h2> | |
<p>Name: {{ [firstName, middleName, lastName] | multiString }}</p> | |
` | |
}) | |
export class NameFormatComponent implements OnInit { | |
@Input() firstName: string = 'George'; | |
@Input() middleName: string = 'P'; | |
@Input() lastName: string = 'Burdell'; | |
constructor() { } | |
ngOnInit() { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment