Angular - Input directive is not updated when a button is clicked

I created a directive in Angular that checks if two controls have a value. If one of them is filled, the other must be filled, so they must be empty or filled. While this is working.

This directive should be disabled by default. It should be activated only after pressing a button. To control this, I have @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" ...

, "" true, . , "", , "enabled" . , ?

.

+4
1

, , setTimeOut , , 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);
}
0

Source: https://habr.com/ru/post/1686180/


All Articles