首先,通过@ViewChild选择日期选择器组件。然后,定义一个名为disableDates的函数,该函数将返回一组要禁用的日期。在ngAfterViewInit生命周期钩子中,调用setAttribute()方法来更新组件中禁用的日期。最后,更新日期时,调用更新函数以刷新禁用的日期。示例代码如下:
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { Ng2BootstrapModule } from 'ng2-bootstrap'; import * as moment from 'moment';
@Component({ selector: 'app-datepicker', templateUrl: './datepicker.component.html' }) export class DatepickerComponent { @ViewChild('datepicker') datepicker;
// define function to return disabled dates disableDates(): any { let now = moment(); return { daysOfWeek: [0, 6], daysOfMonth: [1, 2, 3, 4, 5], dates: [now.add(1, 'M').add(2, 'd')] }; }
// update disable dates updateDisableDates(): void { let dates = this.disableDates(); this.datepicker.setAttribute('options', '{ "disable": ' + JSON.stringify(dates) + ' } '); }
// call update function when dates change onDateChange(): void { this.updateDisableDates(); }
// call update function when component initializes ngAfterViewInit(): void { this.updateDisableDates(); } }
请注意,moment.js库是在此示例中使用的日期库之一,仅供参考。actual example may use a different library or approach.