【问题标题】:ngx datepicker: set initial year value from previous yearsngx datepicker:设置前几年的初始年份值
【发布时间】:2020-01-14 06:52:54
【问题描述】:

我在 Angular 8 中使用 ngx datepicker,我想将年份(日历)设置为从今天开始 18 年。 我正在使用这里的示例https://stackblitz.com/edit/angular-ripj4g?file=app/ngx-bootstrap-demo.component.ts

此示例设置 minDate 和 maxDate,我如何设置初始日期/年份,即当下拉菜单打开时将显示 2002 年。

【问题讨论】:

    标签: angular


    【解决方案1】:

    这样试试

    component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'demo-datepicker-min-max',
      templateUrl: './min-max.component.html'
    })
    export class DemoDatepickerMinMaxComponent {
      minDate: Date;
      maxDate: Date;
      currentData: Date;
    
      constructor() {
         this.minDate = new Date();
         this.maxDate = new Date();
         this.currentData = new Date();
         this.currentData.setFullYear(this.minDate.getFullYear() -3);
         this.minDate.setFullYear(this.minDate.getFullYear() -3);
         console.log(this.minDate);
         this.maxDate.setDate(this.maxDate.getDate() + 7);
      }
    }
    

    component.html

    <div class="row">
      <div class="col-xs-12 col-12 col-sm-6 col-md-4 form-group">
        <input class="form-control"
               placeholder="Datepicker"
               [(ngModel)]="currentData"
               bsDatepicker
               [minDate]="minDate"
               [maxDate]="maxDate">
      </div>
    </div>
    

    【讨论】:

    【解决方案2】:

    我已根据文档进行了更改

    https://valor-software.com/ngx-bootstrap/#/datepicker

    改变你的html就像

    <div class="row">
        <div class="col-xs-12 col-12 col-sm-6 col-md-4 form-group">
            <input class="form-control"
               placeholder="Datepicker"
               bsDatepicker
               [bsValue]="bsValue"
               [minDate]="minDate"
               [maxDate]="maxDate">
      </div>
    </div>
    

    在你的 ts 文件中

    import { Component } from "@angular/core";
    @Component({
      selector: "demo-datepicker-min-max",
      templateUrl: "./min-max.component.html"
    })
    export class DemoDatepickerMinMaxComponent {
      minDate: Date;
      maxDate: Date;
      bsValue = new Date();
      constructor() {
        this.minDate = new Date();
        this.maxDate = new Date();
        this.minDate.setFullYear(this.minDate.getFullYear() - 18);
        console.log(this.minDate);
        this.maxDate.setDate(this.maxDate.getDate() + 7);
        this.bsValue = new Date(
          new Date().setFullYear(new Date().getFullYear() - 18)
        );
      }
    }
    

    这是输出 希望对你有帮助

    谢谢

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多