簡體   English   中英

角度材料mat-error無法顯示消息

[英]Angular material mat-error cannot show message

我有2個日期時間選擇器,endDate不能小於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;
  }

在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>

如果出現“mat-error”,則不顯示該消息。 我嘗試改變“小”

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

信息很好。 請告訴我如何使用mat-error

mat-error僅在FormControl無效時顯示,但您在表單組上進行了驗證。 因此,在這種情況下,您需要使用ErrorStateMatcher

在你的情況下,它看起來像這樣:

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);
  }
}

另外值得一提的是,不建議使用兩個綁定,即formControlngModel 刪除ngModel並使用表單控件。 如果您稍后收到開始日期和結束日期,則可以使用patchValue (僅設置一些值來形成)或setValue (將所有值設置為表格)

在組件中標記errorstatematcher:

matcher = new MyErrorStateMatcher();

至於您的自定義驗證器,您不需要解析日期,只需檢查結束日期是否小於開始日期:

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

然后在模板中標記錯誤狀態匹配器:

<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>

這是StackBlitz

如果要手動將.ts文件中的控件設置為無效...

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' //

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM