0

I have the following template:

<input type="text" class="form-control" name="my_date" 
  [matDatepicker]="myDatepicker" #myDate="ngModel"        
  [(ngModel)]="myDateValue" id="my_date" required>                                        
<mat-datepicker-toggle [for]="myDatepicker"></mat-datepicker-toggle>                                                                                
<mat-datepicker #myDatepicker></mat-datepicker>  
<div *ngIf="myDate.errors && (myDate.touched || cFormDirective.submitted)">                                                   
  <div *ngIf="myDate?.errors?.required">            
    Please enter date
  </div>                                            
</div>  

When clicking submit the style for the input textbox applied correctly in red correctly but the message not shown.

As you can see this a template driven form and I don't wish to update it now to reactive form just because of the date, also I don't use mat form field cause a different design when doing so.

Any idea how can I show the message ?

SuperStar518
  • 2,814
  • 2
  • 20
  • 35
user2304483
  • 1,462
  • 6
  • 28
  • 50

1 Answers1

0

I think that the problem is this cFormDirective.submited. use a template reference equal to ngForm, like

<form #myform="ngForm" (submit)="submit()">
    <mat-form-field>
        <input name="myDate" matInput [matDatepicker]="picker"
       placeholder="Choose a date" required 
         [(ngModel)]="myDateValue" #myDate="ngModel">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
  <mat-error *ngIf="myDate?.errors?.required">Please, enter date</mat-error>
</mat-form-field>
<div *ngIf="myDate.errors && (myDate.touched || myform.submitted)">                                                   <div *ngIf="myDate?.errors?.required">          
            Please enter date
    </div>                                          
</div> 
<button typpe="submit">click</button>
</form>

By the way if you use <mat-error> you avoid some complex

Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • cFormDirective is like your # myForm directive so that's not the issue, I've tried mat-error with no success. I think materror is good when you're using mat input which I don't. – user2304483 Jun 24 '19 at 08:28
  • 1
    I make a stackblitz: https://stackblitz.com/edit/angular-dcckzs?file=app/datepicker-overview-example.html. Take account that required only say that the value is null – Eliseo Jun 24 '19 at 08:32