【问题标题】:Angular Material 6 datepicker's close button prevents view from updatingAngular Material 6 datepicker 的关闭按钮阻止视图更新
【发布时间】:2018-06-28 23:50:09
【问题描述】:

我的表单中有一个日期选择器,它假设只捕获月份和年份。在 html 中,我有一个 div,我在其中显示选定的月份和年份。

为此,我关注了Watching the views for changes on selected years and months tutorial

我对教程中的代码做了一些更改。 打字稿

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(); 行然后查看更新。

我在这里做错了什么。我是角度和角度材料的新手。

【问题讨论】:

    标签: angular view datepicker angular-material


    【解决方案1】:

    自己想出来的

    TS

    this.jointForm.controls.month.valueChanges.subscribe(
            (value) => {
                this.filters.month = value;
    
                if(value !== null){
                    this.filters.month = value.format('MMM YYYY');
                }
            }
        );
    

    HTML

    <span>{{ filters.month }}</span>
    

    这似乎是一种肮脏的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2020-06-27
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2019-03-22
      相关资源
      最近更新 更多