I've created a directive in Angular that checks if two controls have value. If one of them has been filled, the other must be filled too, so they have to be both empty or both filled. This is working fine so far.
This directive must be disabled by default. It only must be enabled after pressing a button. To control this, I have an @Input in the directive where I bind the variable that the button sets to 'true':
import { Validator, FormControl, NG_VALIDATORS, FormGroup, NgForm } from '@angular/forms';
import { Directive, forwardRef, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[correquired][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => CorrequiredDirective), multi: true }
]
})
export class CorrequiredDirective implements Validator {
@Input() other: FormControl;
@Input() enabled: boolean;
validate(c: FormControl): { [index: string]: any; } {
if (!this.enabled) { return null; }
if (this.other != null && this.other.value != null && this.other.value.trim && this.other.value.trim() === '') {
this.other.setValue(null);
}
if (c.value != null && c.value.trim && c.value.trim() === '') {
c.setValue(null);
}
if (c.value != null && c.value != undefined) {
this.other.markAsTouched();
}
if (this.other != null && c.value == null && this.other.value != null) {
return { 'correquired': { valid: false } };
}
}
}
And, in the component, I set the control this way:
<input type="text" correquired [other]="form3.controls['delivered_quantity']" [enabled]="publishing" ...
The button that sets the variable "publishing" to true also submits the form. The problem is that when pressing this button, the directive is being executed before changing the value of "publishing" and not after that, so the "enabled" variable in the directive is always false. How can I update it when pressing the button?
Thanks in advance.
Ok, I could solve it by adding a setTimeOut in the method called by the button, when setting the variable to true:
publish() {
this.publishing = true;
setTimeout(() => {
if (this.form3.control.controls['delivered_quantity'] != null) {
this.form3.control.controls['delivered_quantity'].updateValueAndValidity();
}
if (this.form3.control.controls['delivered_no'] != null)
this.form3.control.controls['delivered_no'].updateValueAndValidity();
if (this.formsValid && this.radioForm.valid) {
if (this.formsDirty) {
this.doSave()
.add(() => {
this.doPublish();
});
} else {
this.doPublish();
}
}
}, 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With