基于浏览器位置/设置的Angular 2 Datepipe格式 [英] Angular 2 Datepipe formatting based on browser location/settings

查看:273
本文介绍了基于浏览器位置/设置的Angular 2 Datepipe格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使日期管道动态化,以便如果它是美国浏览器日期管道返回美国格式(yyyy / MM / dd),当它是欧洲浏览器它返回欧洲格式(dd / MM / yyyy) ?



谢谢

解决方案

AOT。它通常会要求你做不同的构建。



数据管:

  @Pipe({name:'datepipe',pure:true})
export class MyDatePipe extends DatePipe implements PipeTransform {
构造函数(private win:WindowRef){
super(win.ln) ;
}

transform(value:any,pattern ?: string):string | null {
return super.transform(value,pattern);




$ p



$ b

 函数_window():any {
//返回全局原生浏览器窗口对象
return window;

$ b @Injectable()
导出类WindowRef {
get nativeWindow():any {
return _window();
}

public ln ='en';


构造函数(){
尝试{
if(!isNullOrUndefined(this.nativeWindow.navigator.language)&&&& this.nativeWindow.navigator.language !==''){
this.ln = this.nativeWindow.navigator.language;
}
}终于{}
}
}


Is there a way to make the datepipe dynamic so that if it's an American browser the datepipe returns the American format (yyyy/MM/dd) and when it's a European browser it returns the European format (dd/MM/yyyy)?

Thanks

解决方案

This can be hard, especially when using aot. It would normally require you to make different builds. I extended the datapipe and use the browsers locale.

Datepipe:

@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);
  }
}

Window:

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格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆