Seperate input and calendar on ngx-bootstrap's datepicker

时间:2017-12-18 05:44:21

标签: angular ngx-bootstrap

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.

1 个答案:

答案 0 :(得分:1)

您可以使用ngx-bootstrap提供的ComponentLoaderFactory 它更容易 只需查看https://github.com/valor-software/ngx-bootstrap/blob/4a7f2f0ed720d159430961f7acddfd781628561c/src/datepicker/bs-datepicker.component.ts

即可

作为样本

在组件加载器内部,您可以找到如何注入组件的示例:)