gpt4 book ai didi

Angular 7 : How to re-validate control when a property of the model changes

转载 作者:行者123 更新时间:2023-12-05 07:26:00 24 4
gpt4 key购买 nike

我有一个模板驱动的表单,它有一个输入控件,我需要使用自定义验证器来验证我模型中的属性值(根据下拉列表中的选择动态更改)。每当我在输入控件中键入时它都可以正常工作,但我希望在属性值更改时也进行验证(而不必更改输入框中的值)。有办法实现吗??

下面是模型、标记和我正在使用的验证器的简化版本

型号:

 amountToInvest: number = null;
public onAccountSelectionChanged(event): void {
// find the account based on the selection from this drop down list
this.availableFunds = account.AvailableFunds;
}

标记

<form name="form" (ngSubmit)="myForm.form.valid && onSubmit()" >
<input type="number" [(ngModel)]="amountToInvest"' [customMax]="availableFunds">

验证器

@Directive({
selector: '[customMax][formControlName],[customMax][formControl],[customMax][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomMaxDirective, multi: true}]
})
export class CustomMaxDirective implements Validator {
@Input()
customMax: number;

validate(c: FormControl): {[key: string]: any} {
let v = c.value;
return ( v > this.customMax)? {"customMax": true} : null;
}

最佳答案

我所做的是手动发送一个事件

   const event = new Event('change', { bubbles: true, cancelable: false }); //Create an event
let siblingInput = ele.parentNode['previousElementSibling']['firstChild'] as HTMLInputElement; //Get the element
siblingInput.dispatchEvent(event); //Dispatch event

这将使控件重新生效

关于 Angular 7 : How to re-validate control when a property of the model changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590833/

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