Skip to content
Advertisement

Angular Date Picker is always invalid

I have an angular date picker within a reactive form with a required validator. The problem is that it is always not valid, even when a date is picked. Strangely the control does not display red when it is invalid. Do I need to do some manual css rules for this? HTML and Typescript below. A stackblitz of the issue is here https://stackblitz.com/edit/angular-ewa1kj-vv5baj?file=app/input-error-state-matcher-example.ts

I’ve tried with a without an errorStateMatcher on the date picker — same result

Thanks

Pete

HTML:

    <form [formGroup]="ticketForm" class="example-form" (ngSubmit)="submitForm()">
  <div formGroupName="systemForm">
    <div fxLayout="column" fxLayoutAlign="left center" fxLayoutGap="15px">
      <mat-label>Lateral: *</mat-label>
      <mat-radio-group name="lateral" required formControlName="lateral">
        <mat-radio-button value=1>Yes</mat-radio-button>
        <mat-radio-button value=2>No</mat-radio-button>
      </mat-radio-group>
      <mat-form-field appearance="outline">
        <mat-label>Mark Date</mat-label>
        <input matInput [matDatepicker]="pickerMarkDate" required [errorStateMatcher] = matcher>
        <mat-datepicker-toggle matSuffix [for]="pickerMarkDate"></mat-datepicker-toggle>
        <mat-datepicker #pickerMarkDate></mat-datepicker>
      </mat-form-field>
    </div>
  </div>
/*same result with and without the errorStateMatcher*/
      <button type="submit" mat-stroked-button>Submit</button>
    </form>

TypeScript:

export class InputErrorStateMatcherExample {
  @Input() markDateValid: string;
  @Input() lateralValid: string;
  ticketForm = new FormGroup({
    systemForm: new FormGroup({
      lateral: new FormControl('', [Validators.required]),
      pickerMarkDate: new FormControl('', [Validators.required])
    })
  });

  matcher = new MyErrorStateMatcher();
  submitForm() {
    this.markDateValid = this.ticketForm.get('systemForm').get('pickerMarkDate').valid.toString();//always false
    console.log(this.ticketForm.get('systemForm').get('pickerMarkDate').errors);
    this.lateralValid = this.ticketForm.get('systemForm').get('lateral').valid.toString();
    console.log(this.ticketForm.get('systemForm').get('lateral').errors);
  }
}

Advertisement

Answer

You must add the formControlName directive to link to your formGroup:

<input formControlName="pickerMarkDate" matInput [matDatepicker]="pickerMarkDate">
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement