javascript - Angular 2中的日期选择器问题

标签 javascript jquery angular typescript datepicker

我编写了一个简单的日期选择器程序。并且运作良好。但我现在面临的问题是,如果我需要两个日期选择器,我需要编写两个 jQuery onChange 事件。我需要的是两个使用相同 jQuery onChange 事件的输入日期选择器。在经典的 jQuery 中我可以使用类,但我不知道如何在 typescript 中实现它。任何意见将是有益的。谢谢。

app.component.ts:

  @ViewChild('dateselect') ds: ElementRef;
  ngAfterViewInit() {
    jQuery(this.ds.nativeElement)
      .on('change', () => {
        jQuery(this.ds.nativeElement).attr("data-date", moment(jQuery(this.ds.nativeElement).val(), "YYYY-MM-DD").format('DD MMM YYYY'));

      });
  }

app.component.html

<input type="date" #dateselect name="from" data-date-format="DD/MMM/YYYY">
<!--<input type="date" #dateselect name="to" data-date-format="DD/MMM/YYYY">-->

enter image description here

最佳答案

您一定正在尝试使用日期范围选择器。 我使用了相同的引导日期范围选择器,你可以找到这个 DateRangePicker链接

You needs to add and import daterangepicker.js and daterangepicker.css in your angular 2 ProjectConfig.ts

找到以下代码供您引用。 希望它能更好地帮助您。

tools/config/project.config.ts

import { join } from 'path';
import { SeedConfig } from './seed.config';

export class ProjectConfig extends SeedConfig {
  PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');

  constructor() {
    super();
    this.NPM_DEPENDENCIES = [
        ...this.NPM_DEPENDENCIES,            
        { src: '../../src/client/js/jquery-1.11.1.min.js', inject: 'libs'},
        { src: '../../src/client/js/moment.min.js', inject: 'libs'},
        { src: '../../src/client/js/daterangepicker.js', inject: 'libs' },
        { src: '../../src/client/css/daterangepicker.css', inject: true },
    ];

    // Add `local` third-party libraries to be injected/bundled.
    }
}

app/travel/date-range-picker.html

<div class="form-group">
                <label class="col-sm-4 col-md-4 control-label required-field"><i class="fa fa-suitcase" aria-hidden="true"></i> Travel Dates:</label>
                <div class="col-sm-8 col-md-4 travel-plan-div">
                    <div class="input-group date col-sm-6 from-date" id="fromDate">
                        <input type="text" class="form-control fromdate" placeholder="Start journey" required [(ngModel)]="application.journeyStartDate" [readonly]="true"
                               [ngClass]="{'required-input-field': (applicationform.submitted) && (!startDate.valid)}"
                               id="startDate" name="startDate" #startDate="ngModel">
                    </div>
                    <div class="input-group date col-sm-5 to-date" id="toDate">
                        <input type="text" class="form-control todate" placeholder="End journey" required [(ngModel)]="application.journeyEndDate" [readonly]="true"
                               [ngClass]="{'required-input-field': (applicationform.submitted) && (!endDate.valid)}"
                               id="endDate" name="endDate" #endDate="ngModel">
                    </div>
                    <span class="input-group-addon date-addon">
                        <span class="fa fa-calendar"></span>
                    </span>
                </div>
                <span id="labelNoOfDays" class="travel-days hidden-sm hidden-xs" *ngIf="application.journeyDays > 0">Trip of {{application.journeyDays}} days</span>
            </div>

daterangepicker

app/travel/date-range-picker.component

import {Component, OnInit, Input, Output, EventEmitter, Directive } from '@angular/core';
import {ActivatedRoute, Params, Router } from '@angular/router';
import {AjaxLoader } from '../shared/services/ajax-loader';
declare var jQuery: any;

@Component({
    moduleId: module.id,
    selector: 'date-range-picker',
    templateUrl: 'date-range-picker.html',
    providers: [CommonService,  AjaxLoader]
})

export class DateRangePickerComponent {

ngAfterViewInit() {
       this.setDatepicker();
   }

setDatepicker() {
    var today = new Date();
    let dayDiff: number = 0;

    //jQuery('input[name="startDate"],[name="endDate"], .fa-calendar').daterangepicker({
    jQuery('.fa-calendar').daterangepicker({
        autoUpdateInput: false,
        autoApply: false,
        minDate: today,
        startDate: jQuery('input[name="startDate"').value,
        endDate: jQuery('input[name="endDate"').value,
        showDropdowns: true,
        opens: 'left',
        linkedCalendars: false,
        locale: {
            cancelLabel: 'Clear'
        }
    });

    jQuery('.fa-calendar').on('apply.daterangepicker', (ev: Event, picker: any) => {
        this.application.journeyStartDate = picker.startDate.format('DD/MM/YYYY');
        this.application.journeyEndDate = picker.endDate.format('DD/MM/YYYY');
        this.application.journeyDays = this.calculateJourneyDays(this.getDate(this.application.journeyStartDate), this.getDate(this.application.journeyEndDate));
    });

    jQuery('.fa-calendar').on('cancel.daterangepicker', (ev: Event, picker: any) => {
        this.application.journeyStartDate = null;
        this.application.journeyEndDate = null;
        this.application.journeyDays = 0;
    });
   }

getDate(dateInString: any): Date {
    let array = dateInString.split('/');
    return new Date(array[1] + "/" + array[0] + "/" + array[2]);
  }
}

谢谢。

关于javascript - Angular 2中的日期选择器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40994910/

相关文章:

javascript - 如何在 Angular 应用程序中调用 APP_INITIALIZER

javascript - HTML 实时过滤表

javascript - 使用 jquery 将内联样式添加到动态生成的 div

jquery - 滚动覆盖 HTML 中的 div 元素

javascript - 如何计算 Angular 2中填充的文本框

javascript - 如何将 Angular 4(点击)事件绑定(bind)到动态创建的 div

javascript - 在输入框旁边显示错误而不是 JavaScript 中的 alert()

javascript - 将 G Analytics 集成到 Node.js API

javascript - 谷歌分析异步 : Events Tracking Callback?

javascript - 如何使用 jQuery 检查具有 ID 的 html 元素中的类是否已更改