I'm facing the following problem, maybe some of you know how to solve it. I have a formGroup with different fields, one of them is a date field with a mat date picker. I'm changing programmatically the [max] property of the date picker input but the form is validating always with the first value in the max property and I'm receiving the error "matDatepickerMax". Any idea, As I see the input is working fine and the max value is updated correctly, but the formgroup is validating always with the old value. Thanks in advance
1 Answers
0
votes
@Franco, when you create a validator, the value you pass is the value in the moment. fool example
data={name:'one'}
form=new FormGroup({
name:new FormControl(data.name)
control:new FormControl('',this.foolValidator(data.name))
})
foolValidator(name:string)
{
//only gives error if control.value is "one"
return (control)=>{
return control.value==name?{repeat:true}:null
}
}
If you want take account a variable you can "bind" the validator
data={name:'one'}
form=new FormGroup({
name:new FormControl(data.name)
control:new FormControl('',this.foolValidator().bind(this))
})
foolValidator()
{
return (control)=>{
return control.value==this.form.get('name').value?{repeat:true}:null
}
}
Or create a custom validator like
foolValidator()
{
return (control)=>{
const form=control.parent;
if (form)
{
const name=form.get('name')
return name && control.value==name.value?{repeat:true}:null
}
}
}
In this last case, don't forget, when change "name", make an form.get('control').updateValueAndValidity