问题描述
我正在使用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()
吗?
解决方法
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');
}
}
请检查this 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,day: 10};
}
请参阅this api document以了解更多信息。
,如果要设置任何特定日期,则:
<span>I wanna select this</span>
<span>not this</span>
<br>
<span>not this</span>
<br>
<span>I wanna select this</span>
<span>not this</span>
并使用按钮事件:
"span + span"
<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) {}
请参阅https://stackblitz.com/run?file=src%2Fapp%2Fdatepicker-basic.ts
没有ngAfterViewInit()