Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material mat-error cannot show message

I have 2 datetime picker, endDate cannot be less than startDate

endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp: number;
    var endDateTimestamp: number;
    startDateTimestamp = Date.parse(formGroup.controls['startDateForm'].value);
    endDateTimestamp = Date.parse(formGroup.controls['endDateForm'].value);
    return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
  }

in html:

<mat-form-field>
    <input matInput  name="endDate" id="endDate" formControlName="endDateForm" [(ngModel)]="endDate" [matDatepicker]="toDatePicker"
    placeholder="To Date">
    <mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
    <mat-datepicker disabled="false" #toDatePicker></mat-datepicker>
    <mat-error *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid<mat-error>
</mat-form-field>

with "mat-error", the message does not display. I try to change by "small"

<small *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid</small>

the message well. Please advice me how to using mat-error

like image 334
quoc bao Pham Avatar asked Nov 29 '17 03:11

quoc bao Pham


1 Answers

If you want to set a control as invalid from the .ts file manually...

HTML:

<mat-form-field class="full-width">
  <input matInput [formControl]="exampleFormControl" (change)="changeDetected()">
  <mat-hint>(Optional)</mat-hint>
  <mat-error *ngIf="exampleFormControl.hasError('invalid')">
      Must be a <strong>valid input</strong>!
  </mat-error>
</mat-form-field>

TS:

import { FormControl } from '@angular/forms';

@Component({
  selector: 'derp',
  templateUrl: './derp.html',
  styleUrls: ['./derp.scss'],
})
export class ExampleClass {

  // Date Error Form Control
  exampleFormControl = new FormControl('');

  // Variable Check
  inputValid: boolean;

  changeDetected() {
    // Check if input valid
    if (this.inputValid) {
      console.log('Valid Input');
    } else {
      console.log('Invalid Input');
      // IMPORTANT BIT - This makes the input invalid and resets after a form change is made
      this.exampleFormControl.setErrors({
        invalid: true,
      });
    }
  }

  // CODE THAT CHANGES VALUE OF 'inputValid' //

}
like image 127
About7Deaths Avatar answered Sep 21 '22 12:09

About7Deaths