简体   繁体   中英

Mat error is not getting shown the error message

I am using Mat control date range input control.

I want show error message when user misses to enter start date or end date.

here is my Html

<mat-form-field>
<mat-date-range-input [rangePicker]="pickerDate" disabled="this.form.controls[isCurrentDateChange].value==='False'">
<input formControlName="startDate" matStartDate matInput placeholder="Start date"/>
<input formControlName="endDate" matEndDate matInput placeholder="End date" />
</mat-date-range-input>
<mat-error *ngIf="this.form.controls['endDate'].value=='null'">
Please enter date.</mat-error>
<mat-datepicker-toggle matsuffix [for]="pickerDate"></mat-datepicker-toggle>
<mat-date-range-picker #pickerDate><mat-date-range-picker>
</mat-form-field>

Here is my ts file code

    export class MyComponent implements OnInit{
    form:FormGroup;
    constructor()
    {
    this.form=new FormGroup({
    startDate:new FormControl(null,[Validators.required]),
    endDate:new FormControl(null,[Validators.required])
    
    });
    
    saveForm()
    {
    let editForm=this.form.value;
      if(this.editForm.startDate==null)
      {
        this.editForm.controls['startDate'].markAsTouched();
        return false;
      }
      else if(this.editForm.endDate==null)
      { 
        this.editForm.controls['endDate'].markAsTouched();
        return false;
      }
     else
    {  
     return true;
    }
   }
 }

I have tried diff ways to show error on the UI when Savebutton is clicked, but its not showing. Please let me know if there is any way to show mat error on the UI.

I have tried ngIf as true but its not working for showing the error. Please suggest

From this line:

<mat-error *ngIf="this.form.controls['endDate'].value=='null'">

You are comparing whether the endDate 's value is equal to 'null' which is a string. Thus the <mat-error> will not show when the endDate field is not inputted.


Solution 1

To check whether the endDate 's value is null :

<mat-error *ngIf="!this.form.controls['endDate'].value">
  Please enter date.
</mat-error>

Solution 2

Since you have applied Validators.required in your form control, you can check the validation error as below:

<mat-error *ngIf="this.form.controls['endDate'].errors?.required">
  Please enter date.
</mat-error>

Demo @ StackBlitz

Note: There are quite a lot of errors in your attached code, I suggest that you should test your code first before posting the question. It will help for debugging purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM