AhammadaliPK
AhammadaliPK

Reputation: 3548

Angular 2 pipe or directive ? which is the best one?

I have a couple of date fields in my app. So i need to send date as time-stamp to the database .So I'm planning to write a custom pipe to modify the model value . Will that befit to my need ? or do I need to write custom directive for this ?

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
  transform(value: string, args: string[]): any {
    if (!value) return value;

    return value.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  }
}

Upvotes: 0

Views: 1150

Answers (2)

Simon S.
Simon S.

Reputation: 111

You have it backward. In Angular, pipes are used in the template to show data in a more appropriate way. They are not there to modify your actual data.

I recommend using the ng-bootstrap library (you can find it on Github) to use a proper calendar widget. The model can be configured to return a timestamp.


Edit: Adding example of calling it in the code:

let name = new UserNamePipe().transform(user);

https://stackoverflow.com/a/35159546/5885595

Upvotes: 2

Mihails Akimenko
Mihails Akimenko

Reputation: 104

Hope I understood your question right.
For conversion you can use standard DatePipe (or extend it), for example:

{{ dateField | date:'HH:mm:ss SSS'}}
{{ dateField | date:'HHmmssSSS':'+0000'}}

Upvotes: 0

Related Questions