• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Angular / Thousand Separator Directive

Thousand Separator Directive

Only when typeof number

import {
Directive,
ElementRef,
Input,
Renderer2,
SimpleChanges,
OnInit,
OnChanges,
} from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Directive({
selector: '[appThousandSeparator]',
providers: [DecimalPipe],
})
export class ThousandSeparatorDirective implements OnInit, OnChanges {
@Input('appThousandSeparator') num?: number | string;

constructor(
private el: ElementRef,
private renderer: Renderer2,
private decimalPipe: DecimalPipe
) {}

private updateNumber(): void {
if (typeof this.num === 'number') {
const formattedNumber = this.decimalPipe.transform(this.num, '1.0-0');
console.log('Formatted number: ', formattedNumber);
this.renderer.setProperty(
this.el.nativeElement,
'textContent',
formattedNumber
);
} else if (typeof this.num === 'string') {
this.renderer.setProperty(this.el.nativeElement, 'textContent', this.num);
} else {
this.renderer.setProperty(this.el.nativeElement, 'textContent', '');
}
}

ngOnInit(): void {
this.updateNumber();
}

ngOnChanges(changes: SimpleChanges): void {
if (changes['num']) {
this.updateNumber();
}
}
}

Filed Under: Angular

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved