Get currency symbol angular 2 - javascript

I'm building an application using angular 2 and currency pipe, but I can't find a way to get the currency symbol according to the ISO value without any number. What I mean is that I just want the symbol without setting a number to be formatted.
Normal situation $3.00
I want only the $symbol, not the number

Angular provides an inbuilt method getCurrencySymbol which gives you currency symbol. You can write a pipe as a wrapper over that method as
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(
code: string,
format: 'wide' | 'narrow' = 'narrow',
locale?: string
): any {
return getCurrencySymbol(code, format, locale);
}
}
and then use as:
{{'USD'| currencySymbol}} ===> $
{{'INR'| currencySymbol}} ===> ₹
Live Stackblitz Demo:
App Url: https://angular-currency-symbol-pipe.stackblitz.io
Editor Url: https://stackblitz.com/edit/angular-currency-symbol-pipe

Answered in 2017:
As I ONLY wanted the symbol for the currency, I ended up extending currency pipe with a constant number and return only the symbol. It feels sort of a "hack" to have a constant number, but as i don't want to create new currency maps and I'm not able to provide a number, i think is the easiest way.
Here is what I did:
import { Pipe, PipeTransform } from '#angular/core';
import {CurrencyPipe} from "#angular/common";
#Pipe({name: 'currencySymbol'})
export class CurrencySymbolPipe extends CurrencyPipe implements
PipeTransform {
transform(value: string): any {
let currencyValue = super.transform(0, value,true, "1.0-2");
return currencyValue.replace(/[0-9]/g, '');
}
}
Now I can use it as:
{{ 'EUR' | currencySymbol }} and get '€'
Thanks for your help and ideas!
Update:
Changed accepted answer to Varun's one as in 2020 I would use getCurrencySymbol() to accomplish that task

I know this question is quite old but just if someone happens upon it as I have, Angular has a method to do this without having to do weird and wonderful Regex and string manipulation.
I made the following pipe using the getCurrencySymbol method in #angular/common
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(currencyCode: string, format: 'wide' | 'narrow' = 'narrow', locale?: string): any {
return getCurrencySymbol(currencyCode, format, locale);
}
}

You can use the following code in the template which avoids having to define a new pipe:
{{ ( 0 | currency : currencyCode : 'symbol-narrow' ) | slice:0:1 }}
Where this.currencyCode is set to the three digit currency symbol expected to be shown.

for example
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'removeAFromString'})
export class RemoveAFromString implements PipeTransform {
transform(value: number){
return value.substring(1);
}
}
Now concat the pipes:
{{ portfolio.currentValue | currency : 'AUD' : true : '4.0' | removeAFromString}}

Related

angular round to the nearest integer using pipe

what pipe do we use to round a number to a nearest dollar or integer for example 2729999.61 would be 2730000 .
Is there a way to do this on the angular template like using the number pipe ? like | number or
| number : '1.2-2'
From the docs on DecimalPipe:
The value's decimal representation is specified by the digitsInfo parameter, written in the following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
Of great importance as well:
If the formatted value is truncated it will be rounded using the "to-nearest" method:
So, you want something like number: '1.0-0':
// In your component:
myNumber = 2729999.61;
// And then in your template:
<p>Rounded number: {{ myNumber | number: '1.0-0' }}</p>
// will output 'Rounded number: 2,730,000'
If you want to format your numbers using some other criteria, creating a pipe to do so is easy. Here's an example pipe that just uses Math.round:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'customNumber' })
export class CustomNumberPipe implements PipeTransform {
transform(value: number, ...args: any[]) {
return Math.round(value);
}
}
... and to use it, make sure your pipe is imported as a declaration in your app module, then:
<!-- will output 'Rounded with custom pipe: 2730000' -->
<p>Rounded with custom pipe: {{ myNumber | customNumber }}</p>
Here's a working stackblitz with both options to get you going.

How to use currency pipe to get values upto 2 decimal digits in component?

I have a values like 54781.7622000 , 1123.11. I want this values in a format like $54781.76 , $1123.11.
//import currency pipe
import { CurrencyPipe } from '#angular/common'
//initialize in constructor
constructor(private cp: CurrencyPipe)
this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue));
I have tried sum extra parameters after this value like.
this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue),1.2-2);
But doesnt workout.
You are not passing all the needed parameters to the transform()
This is what the currency pipe transform() accepts in Angular (Source: Angular codebase)
transform(value: any, currencyCode?: string, display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string, locale?: string)
You can fix your issue by passing the right data to the transform() like below.
this.formatedOutputValue = this.cp.transform(this.outputValue, 'USD', 'symbol', '1.2-2');
Here is a working example on StackBlitz. You can also see how to directly use the pipe in the template in this example.
you can do it using currency pipe only
this.cp.transform(this.data,'USD','symbol','1.2-2')
Stackblitz
You can create pipe like this:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'formatedOutputValue'
})
export class FormatedOutputValuePipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.toFixed(2).replace(/[.,]00$/, "");
}
}
In your template:
<div>{{data.value | formatedOutputValue}}</div>
You'll want to use the Currency pipe in your template like this:
{{ outputValue | currency }}
The default decimal point is 2 if a currency code is not specified.
Angular has excellent documentation on how to properly use their CurrencyPipe.

Angular 6: Function call within HTML interpolation returns undefined

I'm attempting to call a function inside my HTML interpolation, like so. This HTML chunk is inside a *ngFor loop.
<mat-list>
<mat-list-item *ngFor="let unit of units">
<div>
<p>Remaining Life</p>
<h2>{{ parseTimeRemaining(unit.daysRemaining) }}</h2>
</div>
</mat-list-item>
<mat-list>
parseTimeRemaining() returns a string to be displayed, using the value of unit.daysRemaining as a parameter.
public parseTimeRemaining(days: number){
const timeString = days + " Days";
return timeString;
}
Currently, my function returns undefined and thus, an empty <h2> element. Did I do something wrong? If so, what's the best way to display the information I need?
This could be a great opportunity to use a Pipe instead of a function. This helps to avoid calling a function within an *ngFor which can have detrimental affects to performance. From the documentation surrounding pipes and change detection.
Angular picks a simpler, faster change detection algorithm when you
use a pipe.
Angular has a built-in pipe, I18nPluralPipe which "Maps a value to a string that pluralizes the value according to locale rules.". You create an object (pluralMap) targeting specific numerical values and indicate the resulting string should be allowing to say 0 Days, 1 Day, or 99 days.
pluralMap = {
'=0': '0 Days',
'=1': '1 Day',
'other': '# Days'
};
You would use it in a template as follows:
<ul>
<li *ngFor="let unit of units">{{ unit.daysRemaining | i18nPlural:pluralMap }}</li>
</ul>
Another approach would be to create a Custom Pipe. This would allow you implement custom formatting and/or validation logic against the provided daysRemaining.
Pipe:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'daysRemaining'})
export class DaysRemainingPipe implements PipeTransform {
transform(days: number): string {
const timeString = days + " Days";
return timeString;
}
}
Module (registration):
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { DaysRemainingPipe } from './days-remaining.pipe';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, DaysRemainingPipe ]
bootstrap: [ AppComponent ]
})
export class AppModule { }
Template:
<ul>
<li *ngFor="let unit of units">{{ unit.daysRemaining | daysRemaining }}</li>
</ul>
Taking it one step further, we could extend the I18nPluralPipe to pluralize the results within our custom pipe by extending the built in pipe and maybe check if the input is a valid number.
import { Pipe, PipeTransform } from '#angular/core';
import { I18nPluralPipe } from '#angular/common';
#Pipe({name: 'daysRemaining'})
export class DaysRemainingPipe extends I18nPluralPipe implements PipeTransform {
transform(days: number): string {
const safeDays = isNaN(days) ? 0 : days;
const pluralMap = {
'=0': '0 Days',
'=1': '1 Day',
'other': '# Days'
};
return super.transform(safeDays, pluralMap);
}
}
Here is an example in action.
Hopefully that helps!
It seems that your function is not returning anything. Check that the function is being called (put a console.log to see if actually is being executed).
However, maybe it would be better something like this.
<h2>{{ unit.daysRemaining + ' Days' }}</h2>
If that works, maybe the problem was a typo, or some scope visibility that you are missing there (is that template the template of the component?)

How I can create Angular custom Date Pipe

I'm working on angular 5 I want to create a custom date pipe that allows me to subtract some days from a date :
This how I display my date value :
<span>{{data.nextCertificateUpdate | date:'yyyy-MM-dd'}}</span>
for example this display a value like : 2018-08-29
I ask if it's possible to create a pipe that allow me to substract a number of days for example 28 from this date ?
Something like :
<span>{{data.nextCertificateUpdate | mypipe:28 }}</span>
and this should display value like : 2018-08-01
Thanks for any help
Adding to the nice answer given by Sachila above, you can also implement the full functionality in your custom pipe itself.
import { Pipe, PipeTransform } from '#angular/core';
import { DatePipe } from '#angular/common';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
// adding a default format in case you don't want to pass the format
// then 'yyyy-MM-dd' will be used
transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
date = new Date(date); // if orginal type was a string
date.setDate(date.getDate()-day);
return new DatePipe('en-US').transform(date, format);
}
}
And use your custom Pipe like:
<span>{{data.nextCertificateUpdate | mypipe: 28: 'yyyy-MM-dd'}}</span>
See a working example here: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html
You can create class for property like wise I have use environment class for date format DATE_FORMAT and assign by default dd-MM-yyyy format and use in date pipe.
By this approach only change the value of DATE_FORMAT and we can easily change the format of date else where.
import { Pipe, PipeTransform } from '#angular/core';
import { environment } from "../../../../environments/environment";
import { DatePipe } from "#angular/common";
#Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
if(Object.keys(environment).indexOf("DATE_FORMAT") >= 0){
return super.transform(value, environment.DATE_FORMAT);
}
return super.transform(value, 'dd-MM-yyyy');
}
html
<span>{{ data.date | dateFormat }}</span>
Create a custom pipe call mypipe
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
transform(date: Date, day: number): string {
date.setDate(d.getDate()-day);
return date;
}
}
call it like this
<span>{{data.nextCertificateUpdate | mypipe:28 | date:'yyyy-MM-dd'}}</span>

Return a pipe through another pipe

This is a follow-up question to Angular2 - assign pipe from a variable
What I'm looking for is a way to use a pipe based on a variable name.
I tried what Günter suggested and created a pipe that returns other pipes, but how would you return another pipe and make sure it's not rendered as text?
I have the following pipe:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'piper'
})
export class PiperPipe implements PipeTransform {
transform(value: any, args?: any): any {
return `{{${value} | ${args}}}`;
}
}
But when I feed it with a date string and "date" argument, like this:
<!-- with e.g. obj = { value: "2016-11-08T11:11:40.000Z", pipe: "date" } -->
<div>{{obj.value | obj.pipe}}</div>
It renders it as innerText:
<div>{{2016-11-08T11:11:40.000Z | date}}</div>
I tried [innerHTML] but no luck either.

Categories