Skip to content

Instantly share code, notes, and snippets.

@krohne
Created October 25, 2021 16:28
Show Gist options
  • Save krohne/a55096509af7621a36e2ce09b90fa385 to your computer and use it in GitHub Desktop.
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
// app.module.ts
import { MultiStringPipe } from './MultiString.pipe';
@NgModule({
declarations: [
//...
MultiStringPipe,
],
})
export class AppModule {}
// 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(),
'');
}
}
// 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