Angular material mat-error cannot show message

后端 未结 2 1513
刺人心
刺人心 2020-12-06 02:11

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

endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp: number;
    var en         


        
相关标签:
2条回答
  • 2020-12-06 02:45

    a mat-error only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use a ErrorStateMatcher

    In your case it would look like this:

    export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const invalidCtrl = !!(control && control.invalid);
        const invalidParent = !!(control && control.parent && control.parent.invalid);
    
        return (invalidCtrl || invalidParent);
      }
    }
    

    Also worth mentioning, it's not recommended to have two bindings, i.e formControl and ngModel. Remove the ngModel and utilize the form control instead. If you receive your start date and end date at a later point, you can use patchValue (just set some values to form) or setValue (set all values to form)

    mark in component the errorstatematcher:

    matcher = new MyErrorStateMatcher();
    

    As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:

    checkDates(group: FormGroup) {
      if (group.controls.endDate.value < group.controls.startDate.value) {
        return { endDateLessThanStartDate: true }
      }
      return null;
    }
    

    and then mark the error state matcher in your template:

    <mat-form-field>
      <input matInput [matDatepicker]="picker2" type="text" formControlName="endDate" [errorStateMatcher]="matcher">
      <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
      <mat-datepicker #picker2></mat-datepicker>
      <mat-error *ngIf="myForm.hasError('endDateLessThanStartDate')">End date cannot be earlier than start date</mat-error>
    </mat-form-field>
    

    Here's a StackBlitz

    0 讨论(0)
  • 2020-12-06 03:03

    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' //
    
    }
    
    0 讨论(0)
提交回复
热议问题