2

我正在使用NgbDatepicker

<ngb-datepicker #dp [(ngModel)]="scheduledStartDate" [ngModelOptions]="{standalone:true}">
</ngb-datepicker>

它可以ngAfterViewInit()像这样完成:

@ViewChild('dp') datepicker: NgbDatepicker;

ngAfterViewInit() {
    this.datepicker.navigateTo({ year: new Date().getFullYear(), month: new Date().getMonth(), day: new Date().getDate() });
}

但是有没有办法navigateTo()在其他功能上使用?

4

2 回答 2

2

NgbDatepicker在初始化之前您无法使用。为了确保它可用,我们有ngAfterViewInit钩子。所以如果你想做一些初始化,你可以在ngAfterViewInit. 但是,如果您仍然想从之前调用的某个函数中使用它view initialisation(假设是构造函数,因为您没有向我们展示您从哪里调用它),您可以使用它setTimeout作为一种解决方法,但我不建议这样做。例如,请参见下面的组件 -

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {

  @ViewChild('dp') datepicker: NgbDatepicker;
  scheduledStartDate: NgbDateStruct = {year: 2222, month: 10, day: 10};
constructor(private calendar: NgbCalendar) {
  console.log(this.datepicker? 'NgDatePicker is available': 'NgDatePicker not initialized');
  setTimeout(() => {
    this.datepicker.navigateTo({year:2090, month: 10});
  }, 1000);
}
ngAfterViewInit() {
    console.log(this.datepicker? 'NgDatePicker is available': 'NgDatePicker not initialized');
}
}

请检查这个 stackblitz例子,它工作得很好。有app.component.html两个按钮可以导航到两个不同的年份。

更新

你也可以startDate在你的<ngb-datepicker>-

<div *ngIf="addEditForm">
    <ngb-datepicker #dp [(ngModel)]="scheduledStartDate"  [startDate]="scheduledStartDate" (navigate)="date = $event.next" *ngIf="addEditForm"></ngb-datepicker>
 </div>

然后不断改变scheduledStartDate而不是使用this.datepicker.navigateTo({})

openAddForm() {
    this.addEditForm = true;
    this.scheduledStartDate = {year: 5555, month: 10, day: 10};
  }

请参阅此 api 文档以了解更多信息。

于 2020-09-10T07:48:29.613 回答
0

如果要设置任何特定日期,则:

<ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>

并使用按钮事件:

<button class="btn btn-sm btn-outline-primary mr-2" (click)="dp.navigateTo()">To current month</button>

<button class="btn btn-sm btn-outline-primary mr-2" (click)="dp.navigateTo({year: 2021, month: 2})">To Feb 2021</button>

和在组件 -

import {NgbDateStruct, NgbCalendar} from '@ng-bootstrap/ng-bootstrap'; export class NgbdDatepickerBasic {

model: NgbDateStruct; date: {year: number, month: number};

constructor(private calendar: NgbCalendar) {}

selectToday() {this.model = this.calendar.getToday();} }

参考https://stackblitz.com/run?file=src%2Fapp%2Fdatepicker-basic.ts

没有 ngAfterViewInit()

于 2020-09-16T12:19:54.527 回答