Search code examples
angularngx-bootstrap

Seperate input and calendar on ngx-bootstrap's datepicker


I want to seperate input and calendar on ngx-bootstrap's datepicker. Then I want to insert the body of the datepicker into a specific tag.

So this is the code i wrote, please take your time to read it

date.component.ts

import {
  Component, OnInit, OnDestroy, ViewChild, ComponentFactoryResolver, ViewContainerRef, Injector
} from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { BsDatepickerContainerComponent } from 'ngx-bootstrap/datepicker/themes/bs/bs-datepicker-container.component';

@Component({
  selector : 'app-date',
  templateUrl : './date.component.html'
})

export class DateComponent implements OnInit, OnDestroy {
  factory: any;
  injector: any;
  config: BsDatepickerConfig;
  instance: any;

  @ViewChild('dp', {read: ViewContainerRef}) dp;

  constructor(
    private resolver: ComponentFactoryResolver
  ) {
  }

  ngOnInit() {

    this.config = new BsDatepickerConfig();

    const minDate  = new Date(1900, 1, 1);
    const maxDate = new Date();
    maxDate.setHours(11, 59, 59, 999);

    this.config.minDate = minDate;
    this.config.maxDate = maxDate;
    this.config.showWeekNumbers = false;

    this.injector = Injector.create([{provide: BsDatepickerConfig, useValue: this.config}]);

    this.factory = this.resolver.resolveComponentFactory(BsDatepickerContainerComponent);

    this.instance = this.makeInstance(this.dp);

  }

  makeInstance(view: ViewContainerRef) {
    view.clear();
    const component = this.factory.create(this.injector);
    view.insert(component.hostView);
    return component.instance;
  }

  ngOnDestroy() {
  }
}

date.component.html

<div #dp></div>

Are there any problems with this code, please share tour thougths.


Solution

  • You can use ComponentLoaderFactory provided by ngx-bootstrap it's much easier just check https://github.com/valor-software/ngx-bootstrap/blob/4a7f2f0ed720d159430961f7acddfd781628561c/src/datepicker/bs-datepicker.component.ts

    as a sample

    inside of component loader you can find a sample how to inject components too :)