这是因为ng2-flatpickr指令在更新表单控件时没有做出变化检测,所以需要手动调用变化检测。在组件类中注入ChangeDetectorRef,并在ngAfterViewInit生命周期钩子中手动调用markForCheck方法。
import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { Ng2FlatpickrDirective } from 'ng2-flatpickr/ng2-flatpickr.directive';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements OnInit { data: any = {}; @ViewChild('datePicker') datePicker: Ng2FlatpickrDirective;
constructor(private cdr: ChangeDetectorRef) {}
ngOnInit() {}
ngAfterViewInit() { this.cdr.markForCheck(); this.datePicker.setElementValue(this.data.date); } }