如何在BsDaterangepickerDirective(NGX日期范围选择器)中动态更改bsConfig

时间:2018-10-10 09:13:32

标签: angular ngx-bootstrap

模板代码

<input type="text" class="form-control" #drp="bsDaterangepicker" bsDaterangepicker [(bsConfig)]="customBsConfig">

打字稿代码

@ViewChild('drp') dataRangePicker: BsDaterangepickerDirective;
customBsConfig: object;

ngOnInit() {
    this.translate.use().subscribe(
        () => {
            this.customBsConfig = Object.assign({}, {
                rangeInputFormat: "MMM-dd-yyyy"
            });
            this.dataRangePicker.setConfig();
        }
    }
); 

Date Range Picker可以正常工作,但是我需要动态更改bsConfig。 (这里我正在使用ngx翻译服务。因此,当语言被动态加载时,日期范围选择器的rangeInputFormat也应该被应用/更新)。如何实现呢?有可能吗?

1 个答案:

答案 0 :(得分:0)

进行3个小时的调试以找出解决方法:

@ViewChild('dataRangePicker') dataRangePicker: BsDaterangepickerDirective;
customBsConfig: Partial<BsDatepickerConfig> = new BsDatepickerConfig();
dateRange: Date[];
range = {
    start: new Date(),
    end: new Date()
};

format = {
  "en-us" : 'MM/DD/YYYY',
  "en-gb" : 'DD/MM/YYYY',
  "ge": "DD.MM.YYYY"
};

constructor() {
    this.calanderConfigInit();
}

ngOnChanges() {
    this.translate.use().subscribe(
        (langChanged) => {
            this.calanderConfigChange();
        });
}

selectDate() {
    this.range.start = this.dateRange[0] 
    this.range.end = this.dateRange[1]
}

calanderConfigInit() {
    const langChoosen = "en-us"; // get current language;
    this.environmentBS.rangeInputFormat = format[langChoosen];
}

calanderconfigChange() {
  // clear the ngmodel of datepicker and re-assign it same values which we stored earlier during change event.
  this.dateRange = [];
  this.dateRange = [this.range.start,this.range.end];

  // required format based on condition.
  this.customBsConfig.rangeInputFormat = format[langChanged];
  this.dataRangePicker.setConfig();
}

在HTML中:

<input type="text" class="class" bsDaterangepicker
       #dataRangePicker="bsDaterangepicker" [(ngModel)]="dateRange"
       (ngModelChange)="selectDate()" [maxDate]="maxDate"
       [minDate]='minDate' [bsConfig]="customBsConfig">