-2
I have the following code in the constructor of my component:
this.form = new FormGroup({
id_periodo_ini: new FormControl(undefined),
id_periodo_fim: new FormControl(undefined)
})
In the ngAfterContentInit()
i try to add a custom Validator:
ngAfterContentInit(): void {
this.form.get('id_periodo_ini').setValidators([
Validators.required,
this.periodoService.comparaPeriodo(
this.form.get('id_periodo_ini').value,
this.form.get('id_periodo_fim').value
)
])
this.form.get('id_periodo_fim').setValidators([
Validators.required,
this.periodoService.comparaPeriodo(
this.form.get('id_periodo_ini').value,
this.form.get('id_periodo_fim').value
)
])
}
In my periodService, the method code comparaPeriodo()
is like this:
public comparaPeriodo(periodoInicial: Periodo, periodoFinal: Periodo): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
console.log(periodoFinal, periodoInicial)
if (
(periodoInicial && periodoFinal) &&
(periodoInicial.dt_inicial && periodoFinal.dt_inicial)
) {
console.log(periodoInicial, periodoFinal)
if (periodoFinal.dt_inicial < periodoInicial.dt_inicial) {
console.log("Invalido")
return {
periodoInvalido: "O período inicial deve ser anterior ao período final"
}
}
}
return null;
}
}
Only when I change the value of the fields "id_periodo_ini
" and "id_periodo_fim
" is always null.
I already put a (selectionChange)
in the mat-select
and there it is taking the correct value, but when it calls the "comparaPeriodo()
" always appears null
.
What else do I have to do to put a custom Validator?
Thanks in advance.