首页 > 解决方案 > 将多个输入参数分配给 Angular Validator

问题描述

我的 Angular 8 项目中有一个一次性自定义验证器,用于根据另一个输入的值确定是否需要输入。

@Directive({
    selector: '[appRequiredExplanation]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: RequiredHardshipDirective,
            multi: true
        }
    ]
})
export class RequiredExplanationDirective implements Validator {
    @Input('appRequiredExplanation') otherValue = '';

    validate(control: AbstractControl): { [key: string]: any } | null {
        return this.otherValue === MyComponent.needsExplanationReason &&
        control.value === ''
            ? { required: { value: control.value } }
            : null;
    }
}

当前@InputotherValue是第一个单选组的表单值。MyComponent.needsExplanationReason是一个静态属性,包含需要附加信息的第一个单选组的值。

我现在有另一个具有相同范例的组件,我想通过@Input为该静态属性创建另一个来使其可重用。

现在,我在我的 HTML 中像这样访问它:

<textarea
    name="mainReasonExtraInfo"
    placeholder="Please provide additional information"
    [(ngModel)]="model.mainReasonExtraInfo"
    appRequiredExplanation="model.mainReason"
></textarea>

如果我向 Validator 添加另一个,我将@Input如何在 DOM 中提供该信息?

标签: angularvalidation

解决方案


Angular 文档确实涵盖了如何做到这一点。我试过谷歌搜索,但它从未出现在前两页上。

您可以简单地@Input向指令添加另一个,然后继续向您的 DOM 元素添加更多属性。

export class RequiredExplanationDirective implements Validator {
    // Providing the name here allows us to assign a value to the declaration call.
    @Input('appRequiredExplanation') otherValue = '';
    @Input() compareValue = '';

    validate(control: AbstractControl): { [key: string]: any } | null {
        return this.otherValue === this.compareValue &&
        control.value === ''
            ? { required: { value: control.value } }
            : null;
    }
}

然后在您的 DOM 中将其设置为另一个属性。

<textarea
    name="mainReasonExtraInfo"
    placeholder="Please provide additional information"
    [(ngModel)]="model.mainReasonExtraInfo"
    appRequiredExplanation="model.mainReason"
    compareValue="needsExplanationReason"
></textarea>

推荐阅读