Здесь обновляется рабочий код
Файл Customvalidator: profilecustome.validator.ts
import { AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export class ProfileCustomValidators {
static validateTime(): ValidatorFn {
return (c: AbstractControl) => {
const fromTime = c.get('fromTime').value;
const toTime = c.get('toTime').value;
if(fromTime > toTime) {
return {
'toTime': true
}
}
return null;
};
}
}
module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import {
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule
} from '@angular/material';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ ReactiveFormsModule, BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
exports: [ MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule ],
})
export class AppModule { }
component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, ValidationErrors, FormBuilder, FormControl, Validators } from '@angular/forms';
import { ProfileCustomValidators } from "./custom-validators/profilecustome.validator";
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
staffForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.staffForm = this.fb.group({
fromTime: new FormControl(null, Validators.required),
toTime: new FormControl(null, Validators.required),
}, {
validator: ProfileCustomValidators.validateTime()
});
}
}
component.html
<div>
<form [formGroup]="staffForm">
<mat-form-field>
<input
type="time"
required
formControlName="fromTime"
matInput
/>
</mat-form-field>
<mat-form-field>
<input
type="time"
required
formControlName="toTime"
matInput
/>
</mat-form-field>
<div *ngIf="staffForm.hasError('toTime')">End time should be greater than start time</div>
</form>
</div>
Надеюсь, это поможет вам.Пожалуйста, проверьте это рабочее демо на https://stackblitz.com/edit/angular-gsk5xu