Angular 7 从 Kendo UI 日期选择器获取所选日期的值

Angular 7 getting value of selected date from Kendo UI date picker

我的应用程序 Component.html 有一个基本的导航和一个日期选择器,就像这样...

<div class="container-fluid">
    <div class="row">

<!-- Navigation Removed -->          
        <div class="col-md-2 float-right">
            <kendo-datepicker
                (valueChange)="onChange($event)"
                [(value)]="value">
            </kendo-datepicker>
        </div>
    </div>
</div>
<router-outlet></router-outlet>

component.ts的设置方式如下:

import { Component, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-root',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @Input() value: Date = new Date();
  @Output() dateChanged: EventEmitter<Date> = new EventEmitter<Date>();

  constructor() {}

  public onChange(value: Date): void {
    this.dateChanged.emit(value);
  }
}

我有一些页面有调用服务的网格控件,但日期目前是硬编码的,一切正常。我希望能够根据从上面的日期选择器中选择的日期刷新网格数据,本质上,我将单击数据选择器,发出的值将传递给具有网格控制器的组件中的方法。

带网格的控制器:

import { Component, OnInit, Input } from '@angular/core';
import { GridDataResult, DataStateChangeEvent } from '@progress/kendo-angular-grid';
import { DataSourceRequestState } from '@progress/kendo-data-query';
import { DataService } from '../services/DataService.service';

import { Observable } from 'rxjs/Observable';
import { State } from '@progress/kendo-data-query';

@Component({
  templateUrl: './grid.component.html',
  styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit {

  public products: GridDataResult;
  public state: DataSourceRequestState = {
      skip: 0,
      take: 25
  };
  @Input() value: Date = new Date();

  constructor(private dataService: DataService) { }

  ngOnInit() {
     this.dataService.fetch(this.state).subscribe(r => this.products = r);
  }

  public dataStateChange(state: DataStateChangeEvent): void {
    this.state = state;
    this.dataService.fetch(state)
        .subscribe(r => this.products = r);
}

}

您可以使用 Subject 来监听日期输入的变化。

首先创建一个日期服务。

@Injectable()
export class DateService {

  public chosenDate: Observable<Date>;
  private dateSubject: Subject<Date>;

  constructor() {
    this.dateSubject = new Subject<Date>();
    this.chosenDate = this.dateSubject.asObservable();
  }

  dateChanged(newDate:Date){
    this.dateSubject.next(newDate);
  }

}

然后在您的网格控制器中,注入此服务并从组件中您需要的服务订阅所选日期。


constructor(private service: DateService){


this.service.chosenDate.subscribe((date: Date) => { 
    // do something useful with date
});

最后在您的日期字段更改事件中,输入此代码以将新日期传递给服务

this.service.dateChanged(date);

编辑:这里我给大家做了一个例子,演示了解决方法。我相信您可以在您的代码中轻松实现这一点。

DEMO