Reputation: 20565
I have an Angular date variable today
that I'm using the date pipe on, like so:
{{today | date:'LLLL d'}}
February 13
However, I would like to make it appear like this:
13 days so far in February
When I try a naive approach to this, I get this result:
{{today | date:'d days so far in LLLL'}}
13 13PM201818 18o fPMr in February
This is because, for instance d
refers to the day.
How can I escape these characters in an Angular date pipe? I tried \d
and such, but the result did not change with the added backslashes.
Upvotes: 46
Views: 18179
Reputation: 158
This works for me:
{{today | date:"d 'days so far in' LLLL"}}
Upvotes: 6
Reputation: 1164
It's sometimes required to double escape the escaping '
character. E.g. when it is being passed as an input to a component or setting a property on an element.
@Component({
selector: 'comment',
template: `
<tooltip
[message]="timeCreated | date: 'EEEE, MMMM d, y \\'at\\' HH:mm a'">
</tooltip>
`
or
@Component({
selector: 'comment',
template: `
<tooltip
message="{{ timeCreated | date: 'EEEE, MMMM d, y \\'at\\' HH:mm a' }}">
</tooltip>
`
Upvotes: 1
Reputation: 3374
How about this:
{{today | date:'d \'days so far in\' LLLL'}}
Anything inside single quotes is ignored. Just don't forget to escape them.
Upvotes: 60
Reputation: 2011
As far as I know this is not possible with the Angular date pipe at the time of this answer. One alternative is to use multiple date pipes like so:
{{today | date:'d'}} days so far in {{today | date:'LLLL'}}
EDIT:
After posting this I tried @Gh0sT 's solution and it worked, so I guess there is a way to use one date pipe.
Upvotes: 3
Reputation: 62213
Then only other alternative to stringing multiple pipes together as suggested by RichMcCluskey would be to create a custom pipe that calls through to momentjs format with the passed in date. Then you could use the same syntax including escape sequence that momentjs supports.
Something like this could work, it is not an exhaustive solution in that it does not deal with localization at all and there is no error handling code or tests.
import { Inject, Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'momentDate', pure: true })
export class MomentDatePipe implements PipeTransform {
transform(value: any, pattern: string): string {
if (!value)
return '';
return moment(value).format(pattern);
}
}
And then the calling code:
{{today | momentDate:'d [days so far in] LLLL'}}
For all the format specifiers see the documentation for format.
Keep in mind you do have to import momentjs
either as an import statement, have it imported in your cli config file, or reference the library from the root HTML page (like index.html).
Upvotes: 1