Angular 提供者:根据@Input() 参数动态提供值

问题描述

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>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...