danielmoncada / date-time-picker

Angular Date Time Picker (Responsive Design)
https://daniel-projects.firebaseapp.com/owlng/date-time-picker
MIT License
137 stars 59 forks source link

Change OWL_DATE_TIME_FORMATS on click event or ngOnInit #191

Open pamanes opened 5 months ago

pamanes commented 5 months ago

hi, I need to be able to change the format of the date time picker either on ngOnInit or in a method called later after initialization. It looks like changing the format in the constructor works fine, but it cannot be changed afterwards. Thanks!

Here's the stackblitz of the setup I have: https://stackblitz.com/edit/angular-vcdudj?file=src%2Fapp%2Fapp.component.ts

Here's the app.component for the sample:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    // `MomentDateTimeAdapter` can be automatically provided by importing
    // `OwlMomentDateTimeModule` in your applications root module. We provide it at the component level
    // here, due to limitations of our example generation script.
    {
      provide: DateTimeAdapter,
      useClass: MomentDateTimeAdapter,
      deps: [OWL_DATE_TIME_LOCALE],
    },
    {
      provide: OWL_DATE_TIME_FORMATS,
      useFactory: (datepickerFormatsProvider: DatepickerFormatsProvider) =>
        datepickerFormatsProvider.getFormats(),
      deps: [DatepickerFormatsProvider],
    },
    DatepickerFormatsProvider,
  ],
})
export class AppComponent implements OnInit {
  public dateTime = new moment();
  constructor(
    private datepickerFormat: DatepickerFormatsProvider
  ) {
    console.log('constructor');

    this.datepickerFormat = datepickerFormat;
    //this one works fine:
    this.datepickerFormat.setFormats(1);//switch values from 1 to 2
  }

  ngOnInit() {      
    console.log('ngOnInit');
    //this one does not work, too late to change the format?
    this.datepickerFormat.setFormats(1);//switch values from 1 to 2
  }

  btnClick(){
    console.log("button was clicked");
    //this one does not work, too late to change the format?
    this.datepickerFormat.setFormats(1);//switch values from 1 to 2, 

    this.dateTime = new moment();
  }
}