我试图借助Angular材质在Angular 7中创建日期范围选择器。但是,每当我单击日历时,输入字段上的值都不会更新。我在下面分享我的代码。
从下面的代码中可以看到,我在第二个输入字段上编写了一个click函数。单击后将打开两个日历,一个日历用于开始日期,另一个日历用于结束日期。但是,每当我尝试单击任何日期时,它仅保存今天的日期。谁能帮我解决这个问题。
input-overview-example.html
<mat-form-field>
<input matInput [matDatepicker]="strtpicker" [value]="date.value" placeholder="Start Date" >
</mat-form-field>
<mat-form-field class="ml-20">
<input matInput [matDatepicker]="endpicker" [value]="date.value" placeholder="Choose a date" (click)="dateRange()">
</mat-form-field>
<div class="d-flex" *ngIf="show">
<mat-card >
<p>Start Date</p>
<mat-calendar ></mat-calendar>
</mat-card>
<mat-card>
<p>End Date</p>
<mat-calendar></mat-calendar>
</mat-card>
</div>
input-overview-example.ts
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';
/**
* @title Basic Inputs
*/
@Component({
selector: 'input-overview-example',
styleUrls: ['input-overview-example.css'],
templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample {
events: string[] = [];
addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
this.events.push(`${type}: ${event.value}`);
}
date = new FormControl(new Date());
show: boolean;
dateRange() {
this.show = true;
}
}
答案 0 :(得分:0)
我不确定为什么将日历与控件分开。但是在这里,我创建了一个示例,说明了如何使用日期选择器范围组件和表单组跟踪数据。本质上结合了Angular Material和Angular Reactive Forms的示例。从本质上讲,需要将输入连接到模型以跟踪更改。
datepicker-overview-example.ts
import {Component, ChangeDetectorRef} from '@angular/core';
import {FormControl, FormGroup } from '@angular/forms';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';
/** @title Basic datepicker */
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {
constructor(private changeDetectorRef: ChangeDetectorRef ) {}
public startDate;
public endDate;
public dateForm = new FormGroup({
start: new FormControl(),
end: new FormControl(),
});
update() {
this.startDate = this.dateForm.get('start').value;
this.endDate = this.dateForm.get('end').value;
}
}
datepicker-overview-example.html
<form [formGroup]="dateForm">
<mat-form-field>
<input matInput [matDatepicker]="start" placeholder="Start Date" formControlName="start" (dateChange)=update()>
<mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
<mat-datepicker #start></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput [matDatepicker]="end" placeholder="End Date" formControlName="end" (dateChange)=update()>
<mat-datepicker-toggle matSuffix [for]="end"></mat-datepicker-toggle>
<mat-datepicker #end></mat-datepicker>
</mat-form-field>
</form>
<h3>Model Output</h3>
<div>
<p>Start: {{startDate}}</p>
<p>End: {{endDate}}</p>
</div>
演示: