我已经创建了一个自定义指令来向现有的matDatePicker控件添加功能。此指令有一个名为format的输入属性,它在运行时提供日期格式。我已经提供了在Angular 2 Material 2 datepicker date format中提到的MyDateAdapter
我的问题是:当我的format的值发生更改时,如何在运行时将输入格式值设置为datepicker日期格式。
我的指令:
@Directive({
selector: '[dateFormat]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: DateFormatDirective,
multi: true
},
{
provide: DateAdapter, useClass: MyDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS
}
]
})
export class DateFormatDirective {
@Input('dateFormat') format: string;
}
MyDateAdapter类和MY_DATE_FORMATS常量refer
发布于 2018-06-10 04:10:14
在查看了material datepicker和NativeDateAdapter源代码后,我找到了上述问题的解决方案。
修改MyDateAdapter
import {TranslateService} from '@ngx-translate/core';
export class MyDateAdapter extends NativeDateAdapter {
format:string;
constructor( private datepipe: DatePipe, platform: Platform,translate: TranslateService) {
super('en', platform);
translate.get('dateFormat').subscribe(ts =>{
this.format=dateFormat;
});
}
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
return this.datepipe.transform(date, this.format);
} else {
return date.toDateString();
}
}
}
新增工厂功能:
export function createDateAdapterLoader (dp: DatePipe, platform: Platform,ts: TranslateService) {
return new MyDateAdapter(dp, platform, ts);
}
修改指令:
import {TranslateService} from '@ngx-translate/core';
import {DatePipe} from '@angular/common';
import {Platform} from '@angular/cdk/platform';
@Directive({
selector: '[dateFormat]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: DateFormatDirective,
multi: true
},
{
provide: DateAdapter,
useFactory: createDateAdapterLoader,
deps: [DatePipe, Platform ,TranslateService]
},
{
provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS
}
]
})
export class DateFormatDirective {
@Input('dateFormat') format: string;
}
您需要在AppModule中提供DatePipe。
这称为工厂提供程序,用于动态创建依赖值!!refer
要从i18n文件中获取格式值,可以使用任何国际化(i18n)库,例如:@ngx-translate
https://stackoverflow.com/questions/50722593
复制相似问题