2

I have an angular form in which there's a required date picker with [min]="now", it's always invalid whatever the date is.

I have two components that have this exact same form, for which I compared the code line by line and there is no difference. One of them is working perfectly while the other one doesn't work for some reason.

component.ts

<div [class.entry]="!form.get('acceptDate').value">
          <mat-checkbox class="checkbox" formControlName="acceptDate"
            ><strong>I accept the date range</strong> -
            {{ enquiry?.timeFrame?.earliest.toDate() | date }} -
            {{ enquiry?.timeFrame?.latest.toDate() | date }}
          </mat-checkbox>
          <br />
          <br />
          <mat-form-field *ngIf="!form.get('acceptDate').value">
            <input
              matInput
              [matDatepicker]="optDate"
              placeholder="Preferred date"
              formControlName="optDate"
              [min]="now"
              required
            />
            <mat-datepicker-toggle
              matSuffix
              [for]="optDate"
            ></mat-datepicker-toggle>
            <mat-datepicker #optDate></mat-datepicker>
          </mat-form-field>
        </div>

  now = new Date().toISOString();

  form = this.fb.group({
    acceptDate: [true, Validators.required],
    optDate: [null],
    acceptTaC: [true, Validators.required],
  });

If I remove the [min]="now", it will work.

1 Answer 1

1

You have 1 field (optDate) that is depending on an other (acceptDate). You should make optDate disabled if you don't need it, because acceptDate is true. Or make it enabled if acceptDate is false. And optDate also should have Validators.required validator, because if acceptDate is false, then the user should add an optDate. Right?

https://stackblitz.com/edit/angular-v5nfgs-x5bzka

By the way, don't you forget to put all this into a <form [formGroup]="form">?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes but that doesn't solve my problem, I actually put my code on stackblitz and it works the way I want it. However for this (unknown) reason... it's not working on my host. There must be something affecting it outside this part of code but I can't figure it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.