【发布时间】:2019-02-16 18:20:59
【问题描述】:
我有一个 Angular 组件,它只是一个呈现值的标签,如果它具有关联的管道,则管道的输出应呈现为标签的值。但我不想声明组件中的所有管道。目前我想使用货币管道和日期管道及其参数。但也许我可以扩展组件以使用其他管道。
您是否会将管道作为组件的输入参数传递,或者您的方法是什么?有什么想法吗?
更新 这里有我的 StackBlitz。如果您可以看到,如果我想使用任何管道,我将管道类型及其参数作为参数传递。该组件还可以在不使用管道的情况下呈现标签。
https://stackblitz.com/edit/angular-label-render
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);
}
}
}
【问题讨论】:
-
如果您不喜欢可用的管道,您可以随时创建自己的管道。我不会将管道作为输入传递。尽量保持简单。让你的组件尽可能的愚蠢。你能做一个 stackblitz 让我们看看你在尝试什么吗?
-
我添加了我的 Stackblitz。
标签: angular