javascript - Angular - 指令的输入在按下按钮时不更新

标签 javascript angular typescript angular2-directives

我在 Angular 中创建了一个指令,用于检查两个控件是否具有值。如果其中一个已被填满,则另一个也必须被填满,因此它们必须都是空的或都被填满。到目前为止一切正常。

默认情况下必须禁用该指令。仅需在按下按钮后启用它。为了控制这一点,我在指令中有一个@Input,我将按钮设置为“true”的变量绑定(bind):

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 } };
        }
    }
}

并且,在组件中,我这样设置控件:

<input type="text" correquired [other]="form3.controls['delivered_quantity']" [enabled]="publishing" ...

将变量“publishing”设置为 true 的按钮也会提交表单。问题是当按下这个按钮时,指令是在更改“publishing”的值之前执行的,而不是之后执行的,因此指令中的“enabled”变量始终为 false。按下按钮时如何更新它?

提前致谢。

最佳答案

好的,我可以通过在将变量设置为 true 时在按钮调用的方法中添加一个 setTimeOut 来解决它:

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);
}

关于javascript - Angular - 指令的输入在按下按钮时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359204/

相关文章:

javascript - 根据用户当前位置查询位置数据库

angular - Ionic2 如何在提供程序中获取 NavController

angular - 如何避免 Angular 9 中复杂 RxJS 管道的内存泄漏?

node.js - groupBy 查询与 nodejs ravendb 客户端

javascript - 如何仅在上次调用后返回类方法结果

javascript - 如何在后续调用 sinon.js stub 时使用不同的函数进行 stub

javascript - 如何使用 jQuery 或 JavaScript 使 div 下的图像不可点击?

Angular2等同于模板继承

javascript - 尝试以 Angular 方式将数据传递给子组件时出现错误

javascript - 如何维护 javascript 事件监听器中的 'correct' 范围?