I have an Angular component and it is just a label which renders a value and if it has an associated pipe, the output of the pipe should be rendered as value of the label. But I don't want to declare all the pipes in the component. Currently I would like to use the currency pipe and the date pipe with their parameters. But maybe I can extend the component to use other pipes.
Would you pass the pipes as input parameter of the component or what would be your approach to achieve that? Any idea?
app.component.ts
<app-custom-label value="10000" title="My Title for a Currency render" datatype="currency" param="EUR"></app-custom-label>
<app-custom-label value="01.10.1980" title="My Title for a Date render" datatype="date" param="dd MMMM"></app-custom-label>
custom.label.component.html
<h1>{{ title }}</h1>
<label> {{ value }} </label>
custom.label.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { DataType } from './type';
import { CurrencyPipe, DatePipe } from '@angular/common';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
registerLocaleData(localeDe, 'de-DE', localeDeExtra);
@Component({
selector: 'app-custom-label',
templateUrl: './custom.label.component.html'
})
export class CustomLabelComponent implements OnInit {
@Input() value: string;
@Input() title: string;
@Input() datatype: DataType;
@Input() param: string;
constructor() {}
ngOnInit(){
if (this.datatype === "currency") {
this.value = (new CurrencyPipe('de-DE')).transform(this.value, this.param, true);
} else if (this.datatype === "date") {
this.value = (new DatePipe('de-DE')).transform(this.value, this.param);
}
}
}
Here you have my StackBlitz. If you can see, I pass a type of a pipe and its params as parameters, if I want to use any pipe. The component could also render a label without using a pipe.