【问题标题】:Angular - Directive's Input not updating when pressing buttonAngular - 按下按钮时指令的输入不更新
【发布时间】:2017-09-22 07:32:09
【问题描述】:

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

默认情况下必须禁用此指令。只有在按下按钮后才能启用它。为了控制这一点,我在指令中有一个@Input,我将按钮设置的变量绑定为'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 } };
        }
    }
}

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

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

将变量“publishing”设置为 true 的按钮也会提交表单。问题是,当按下这个按钮时,指令是在更改“发布”的值之前执行的,而不是在那之后执行的,所以指令中的“启用”变量总是假的。按下按钮时如何更新?

提前致谢。

【问题讨论】:

    标签: javascript angular typescript angular2-directives


    【解决方案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);
    }
    

    【讨论】:

    • 除了setTimeout之外,你有没有遇到过其他方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多