Search code examples
angularngx-bootstrap

How to change dynamically bsConfig in BsDaterangepickerDirective (NGX date range picker)


Template Code

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

Typescript Code

@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 works fine however I need to change the bsConfig dynamically. (Here I'm using the ngx translate service. So when the languages get dynamically loaded the rangeInputFormat of the date range picker also should applied/updated ). How to achieve this? Is it possible ?


Solution

  • Took 3hours of debugging to figure the workaround:

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

    In HTML:

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