问题描述
export const FormatDate = new InjectionToken('FormatDate');
...
@Component({
selector: '...',templateUrl: '...',styleUrls: ['...'],providers: [{ provide: FormatDate,useValue: 'MM.yyyy' }]
})
export class DatePicker {
@Input() format: string
...
}
我想根据输入的 'format' 参数动态提供 'FormatDate'。如果 format === 'short' 那么 useValue: 'MM.yy'。如果 format === 'long' 那么 useValue: 'MM.yyyy'。这可能吗?
解决方法
是的,你可以使用管道来做到这一点。创建一个管道,转换方法应该是这样的(伪代码可能会帮助你创建一个流):
exPipe.ts
transform(format: any) {
return format === 'long' ? fetch value form store or anywhere(MM.yyyy)
: fetch value form store or anywhere(MM.yy) || (MM.yyyy).slice(0,4) // just slice it
}
在模板中你可以这样做(只是一个例子):
<div> {{format | exPipe }}</div>