Search code examples
angularangular-materialangular-reactive-formsmat-datepicker

mat-datepicker reactive form set default value on form reset


I have an Angular Reactive Form using Material where I am setting a date range with two mat-datepickers. I am setting the default min date and max date when I create the form, and all is working fine.

My issue is that when the user resets the form, I want to set my default dates in the form again, for another query. I am attempting to do so by getting the default min and max dates from variables, and using setValue, but the default dates are not showing up in the datepickers as they do in the ngOnInit. When I log to the console, the values are being set in the form controls. Why don't they appear as they do on the ngOnInit?

HTML:

<form novalidate autocomplete="off" spellcheck="false" [formGroup]="searchForm" (ngSubmit) = "submit()">
<div>
    <mat-form-field appearance="outline">
        <mat-label>Search Type</mat-label>
        <mat-select formControlName="searchType" [errorStateMatcher]="matcher">
            <mat-option *ngFor="let s of searchTypes" [value]="s">
                {{s}}
            </mat-option>
        </mat-select>
        <mat-error *ngIf="searchForm.get('searchType').hasError('required')">
            Please select the search type
        </mat-error>
    </mat-form-field>
    <mat-form-field appearance="outline" class="eris-ml-2">
        <mat-label>{{inputLabel}}</mat-label>
        <input matInput formControlName="inputText" [errorStateMatcher]="matcher">
        <mat-error *ngIf="searchForm.get('inputText').hasError('required')">
            This field is required.
        </mat-error>
    </mat-form-field>
    <mat-form-field appearance="outline" class="eris-ml-2">
        <mat-label>Event Types</mat-label>
        <mat-select formControlName="eventTypes" multiple [errorStateMatcher]="matcher">
            <mat-option *ngFor="let e of eventTypes" [value]="e">
                <span>{{e}}</span>
            </mat-option>
        </mat-select>
        <mat-error *ngIf="searchForm.get('eventTypes').hasError('required')">
            Please select the event types you want to review.
        </mat-error>
    </mat-form-field>
</div>
<div>
    <mat-form-field appearance="outline">
        <mat-label>From Date</mat-label>
        <input matInput [min]="minDate" [matDatepicker]="picker1" autocomplete="off" formControlName="beginDate">
        <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
        <mat-datepicker #picker1 color="primary"></mat-datepicker>
        <mat-error *ngIf="searchForm.get('beginDate').hasError('required')">
            From date is required
        </mat-error>
        <mat-error *ngIf="searchForm.get('beginDate').hasError('matDatepickerMin') && !searchForm.get('beginDate').hasError('required')">
            From date cannot be before 11/1/2020.
        </mat-error>
    </mat-form-field>
    <mat-form-field appearance="outline" class="eris-ml-2">
        <mat-label>To Date</mat-label>
        <input matInput [max]="defaultEndDate" [matDatepicker]="picker2" autocomplete="off" formControlName="endDate">
        <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
        <mat-datepicker #picker2 color="primary"></mat-datepicker>
        <mat-error *ngIf="searchForm.get('endDate').hasError('required')">
            To date is required
        </mat-error>
        <mat-error *ngIf="searchForm.get('endDate').hasError('matDatepickerMax') && !searchForm.get('endDate').hasError('required')">
            To date cannot be greater than the current date.
        </mat-error>
    </mat-form-field>
</div>
<div>
    <button mat-raised-button color="primary" type="submit" [disabled]="!searchForm.valid">Submit</button>
    <button class="eris-ml-2" mat-raised-button color="accent" type="reset" (click)="reset()">Reset</button>
</div>

TypeScript ngOnInit:

  ngOnInit(): void {
     this.minDate = new Date(2020,10,1) // 11/01/2020 
     this.defaultEndDate = new Date();
     this.defaultStartDate = new Date(2020,10,1);
     const listUrl = `${this.configService.getSettings().azureApiBaseUri}/api/auditlog/eventtypes/list`;
     this.http.get<string[]>(listUrl).subscribe(data => {
     this.eventTypes = data;
   })

   this.searchForm = this.formBuilder.group({
     searchType: ['', [Validators.required]],
     inputText: [{ disabled: true, value: null}, requiredIfValidator(() => ((this.searchForm.get('searchType').value !== 'EventType') && (this.searchForm.get('searchType').value !== '')))],
     eventTypes: [{ disabled: true, value: null}, requiredIfValidator(() => this.searchForm.get('searchType').value === 'EventType')],
     beginDate: [this.defaultStartDate, Validators.required],
     endDate: [this.defaultEndDate, Validators.required]
   })
 }

Reset method, in typescript:

reset(): void {
   // clear the form, then set the default dates.
   this.searchForm.reset();
   this.searchForm.get('beginDate').setValue(this.defaultStartDate);
   this.searchForm.get('endDate').setValue(this.defaultEndDate);
 }

Solution

  • I think I have the solution for you. You have a problem in the reset button that is <button class="eris-ml-2" mat-raised-button color="accent" type="reset" (click)="reset()">Reset</button>. Here type="reset" main problem why you are unable reset data properly. So, you have remove that part from button and the button will look like <button class="eris-ml-2" mat-raised-button color="accent" (click)="reset()">Reset</button>.
    Note: I have tested some part of your code in stackblitz and my code working there. Please check the link Stackblitz Link