有没有办法让 datepipe 动态化,这样如果它是美国浏览器,datepipe 返回美国格式 (yyyy/MM/dd),当它是欧洲浏览器时,它返回欧洲格式 (dd/MM/yyyy) ?
谢谢
最佳答案
这可能很难,尤其是在使用 aot 时。它通常会要求您进行不同的构建。我扩展了数据管道并使用浏览器语言环境。
日期管道:
@Pipe({name: 'datepipe', pure: true})
export class MyDatePipe extends DatePipe implements PipeTransform {
constructor(private win: WindowRef) {
super(win.ln);
}
transform(value: any, pattern?: string): string | null {
return super.transform(value, pattern);
}
}
窗口:
function _window(): any {
// return the global native browser window object
return window;
}
@Injectable()
export class WindowRef {
get nativeWindow(): any {
return _window();
}
public ln = 'en';
constructor() {
try {
if (!isNullOrUndefined(this.nativeWindow.navigator.language) && this.nativeWindow.navigator.language !== '') {
this.ln = this.nativeWindow.navigator.language;
}
}finally {}
}
}
关于基于浏览器位置/设置的 Angular 2 Datepipe 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45561546/