Reputation: 2815
I'd like to modify the font-weight and color of the trailing zeroes of a number. Using a number pipe I'm able to specify 8 decimals, but I'd like all those added zeroes to have less visual significance than the rest of the number. How can I accomplish this in the most Angular "correct" way possible?
Please see the below image for a visual representation of what I'm trying to accomplish:
Upvotes: 3
Views: 469
Reputation: 1526
You should not achieve this functionality by creating your own custom pipe. This is caused by the fact, that applying custom font color is related to the container where a given text is displayed. Pipes ought to remain independent of the container (they simply manipulate raw data). That is why you should create your own directive. Here you have working example:
@Component ({
selector: 'my-selector',
template: `<div myTextHighlight>1.543020000</div>`
})
export class AppComponent {
}
@Directive({
selector: '[myTextHighlight]'
})
export class HighlightDirective implements OnInit{
private element: ElementRef;
ngOnInit(): void {
setTimeout(()=> {
let originalHTML = this.element.nativeElement.innerHTML;
let whitePart = Number.parseFloat(originalHTML).toString();
let greyPart = originalHTML.substring(whitePart.length, originalHTML.length);
this.element.nativeElement.innerHTML =
`<span style='color: white'>${whitePart}</span>
<span style='color: darkgrey'>${greyPart}</span>`;
});
}
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'black';
this.element = el;
}
}
Upvotes: 5
Reputation: 8879
It's very much possible to use a custom pipe for this effect. You can replace the trailing zeroes in the pipe with your own custom <span>
element with a class that you can style however you want.
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({ name: 'fadeTrailingZeroes', pure: false })
export class FadeTrailingZeroes implements PipeTransform {
constructor(public sanitizer: DomSanitizer) {
}
transform(text: string): SafeHtml {
if (text) {
return this.sanitizer.bypassSecurityTrustHtml(
text.replace(/([0-9]+(\.[1-9]+)?)(\.?0+$)/g,"$1<span class='fade'>$3</span>")
);
} else {
return text;
}
}
}
Here is a working example at StackBlitz.
Please note that the last entry doesn't work, but that is due to my rather bad regex skills. The example should be sufficient enough to prove that it's possible to achieve the desired outcome with a custom pipe.
Upvotes: 0