I got a custom validator that expects a string parameter. However when i change the parameter in code that doesn't change an initial value that was passed during form initialization. The only workaround I found is to remove validator and add it again with new parameter.
Is it a desired behaviour? How can i force angular to "reload" validator parameter?
Code:
HTML
<form [formGroup]="reactiveForm">
<input type="text" formControlName="input">
<button (click)="changeToB()" >switch to b</button>
<br>
valid: {{reactiveForm.get('input').valid}}
<br>
shouldBeEqualTo: {{shouldBeEqualTo}}
</form>
TS
export class AppComponent {
shouldBeEqualTo = 'a';
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reactiveForm = this.fb.group({input: ['a', customValidator(this.shouldBeEqualTo)]})
}
changeToB(){
this.shouldBeEqualTo = 'b';
}
}
export function customValidator(equalTo: string): ValidatorFn{
return (c: AbstractControl): { [key: string]: any } => {
console.log(equalTo)
console.log(c.value)
if(c.value !== equalTo){
return {valid: false};
}
return null;
}
}