У меня в форме есть указатель даты, который должен фиксировать только месяц и год. В html у меня есть div, где я отображаю выбранные месяц и год.
Для этого я следовал Watching the views for changes on selected years and months
учебник .
Я сделал несколько изменений в коде из учебника.
Машинопись
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormGroup, FormControl, NgForm } from '@angular/forms';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
import {Moment} from 'moment';
const moment = _moment;
export const MY_FORMATS = {
parse: {
dateInput: 'MMM YYYY',
},
display: {
dateInput: 'MMM YYYY',
dateMonthYearLabel: 'MMM YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'MMM YYYY',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-joint-form',
templateUrl: './joint-form.component.html',
styleUrls: ['./joint-form.component.scss'],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
]
})
export class JointFormComponent implements OnInit {
calculateFor = [
{value: 'month', viewValue: 'Month'},
{value: 'range', viewValue: 'Range'},
];
jointForm: FormGroup;
isdisable = true;
constructor(private cdRef:ChangeDetectorRef) { }
ngOnInit() {
this.jointForm = new FormGroup({
'calFor' : new FormControl('month'),
'month' : new FormControl(moment().startOf('month')),
'startDate' : new FormControl({value:null, disabled:true}),
'endDate' : new FormControl({value:null, disabled:true}),
});
}
onSubmit(){
console.log('submitted!!', this.jointForm.value)
}
chosenYearHandler(normalizedYear: Moment) {
const ctrlValue = this.jointForm.value.month;
ctrlValue.year(normalizedYear.year());
this.jointForm.patchValue({ 'month' : ctrlValue });
}
chosenMonthHandler(normlizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
const ctrlValue = this.jointForm.value.month;
ctrlValue.month(normlizedMonth.month());
this.jointForm.patchValue({ 'month' : ctrlValue });
// datepicker.close(); //prevents view update
}
disableRange(){
if(this.jointForm.value.calFor == 'month'){
this.jointForm.patchValue({
'startDate' : null,
'endDate' : null
});
this.jointForm.get('startDate').disable();
this.jointForm.get('endDate').disable();
this.jointForm.get('month').enable();
}
else{
this.jointForm.patchValue({
'startDate' : moment(),
'endDate' : moment()
});
this.jointForm.get('startDate').enable();
this.jointForm.get('endDate').enable();
this.jointForm.get('month').disable();
}
}
calForChange(){
this.disableRange();
}
}
HTML
<div class="row">
<div class="col-sm-12">
<mat-card class="example-card">
<mat-card-header>
<mat-card-title><h1>Joints to submit</h1></mat-card-title>
</mat-card-header>
<mat-card-content>
<form [formGroup]="jointForm" (submit)="onSubmit()" >
<div class="row">
<div class="col-sm">
<mat-form-field class="full-width">
<mat-select placeholder="Calculate for" formControlName="calFor"
(selectionChange)="calForChange()">
<mat-option *ngFor="let opt of calculateFor" [value]="opt.value">
{{ opt.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-sm">
<mat-form-field class="full-width">
<input matInput placeholder="Month"
[matDatepicker]="pickMonth" formControlName="month" />
<mat-datepicker-toggle matSuffix [for]="pickMonth"></mat-datepicker-toggle>
<mat-datepicker #pickMonth startView="multi-year"
(yearSelected)="chosenYearHandler($event)"
(monthSelected)="chosenMonthHandler($event, pickMonth)"
panelClass="example-month-picker" ></mat-datepicker>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-sm">
<mat-form-field class="full-width">
<input matInput [matDatepicker]="pickStart" placeholder="Start Date"
formControlName="startDate" >
<mat-datepicker-toggle matSuffix [for]="pickStart"></mat-datepicker-toggle>
<mat-datepicker #pickStart ></mat-datepicker>
</mat-form-field>
</div>
<div class="col-sm">
<mat-form-field class="full-width">
<input matInput [matDatepicker]="pickEnd" placeholder="End Date"
formControlName="endDate" >
<mat-datepicker-toggle matSuffix [for]="pickEnd"></mat-datepicker-toggle>
<mat-datepicker #pickEnd ></mat-datepicker>
</mat-form-field>
</div>
</div>
<button mat-button mat-flat-button type="submit">Fetch</button>
</form>
</mat-card-content>
</mat-card>
</div>
</div>
<div class="row">
<div class="col-sm">
<span><strong>Calculate For : </strong></span>
<span>{{ jointForm.value.calFor }}</span>
</div>
<div class="col-sm">
<span><strong>Month : </strong></span>
<span>{{ jointForm.value.month }}</span>
</div>
<div class="col-sm">
<span><strong>Start Date : </strong></span>
<span>{{ jointForm.value.startDate }}</span>
</div>
<div class="col-sm">
<span><strong>End Date : </strong></span>
<span>{{ jointForm.value.endDate }}</span>
</div>
</div>
Все работает так, как предполагалось, за исключением значения месяца собственности, которое не обновляется в поле зрения. Изменения появляются, когда я нажимаю кнопку выборки. Если я закомментирую строку datepicker.close();
, тогда просматриваю обновления.
Что я здесь не так делаю. Я новичок в угловой и угловой материал.