gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:01:23 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com