使用动态/更新参数的 Angular 7 自定义验证

标签 angular angular-reactive-forms angular-validation angular-validator

我正在使用带有 Material 设计组件的 Angular 7

我需要将 requireMatch 验证添加到 mat-autocomplete 中。

我已经使用参数创建了自定义验证,但参数值确实会动态更改。

下面是我的组件代码。

this.stepFormGroup = this.formBuilder.group({
    AccessCode: ["", [Validators.required, this.requireMatch(this.accessCodeList)]]
});

////require-match validation for access-code
requireMatch = (accessCodes: string[]) => {
    return (control: FormControl) => {
        const selection: any = control.value;
        console.log("accessCodes", accessCodes, "selection", selection);
        if (accessCodes.indexOf(selection)===-1) {
            return { requireMatch: true };
        }
        return null;
    }
}

我面临的问题是,我总是在 requireMatch 内的 accessCodes 中得到空(init)。

this.accessCodeList 的更改不会反射(reflect)到验证器。

这意味着更改 this.accessCodeList 后,它不会在 requireMatch 验证器中获得更新的数组。

那么有人知道如何在自定义验证器中传递动态参数吗?

最佳答案

这样调用时需要绑定(bind)验证函数,否则验证函数不会绑定(bind)输入accessList

[Validators.required, this.requireMatch(this.accessCodeList).bind(this)]

此外,如果您想限制该字段中的某些单词,您可以在此处查看我的 npm 包之一 https://www.npmjs.com/package/ng4-validation

关于使用动态/更新参数的 Angular 7 自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55282111/

相关文章:

javascript - Angular 补丁可观察数据到 react 表单字段

dart - 构建响应式(Reactive)表单时出现运行时错误

javascript - Angular 4 - 在显示验证错误时无法读取 null 的属性状态

angular - 异步验证器未执行

javascript - 将数字字符串转换为逗号版本

angular - 如何访问组件中 FormArray 中定义的 HTML 中的控件 - Angular2

json - Ionic 4 使用搜索栏读取本地 JSON 文件

javascript - Angular Reactive Forms 验证的奇怪错误

angular - 类未定义的 typescript 方法

javascript - 将 JS 库 xml2js 与 Angular 2 结合使用