有条件地应用自定义指令

时间:2018-02-05 21:07:38

标签: angular

我创建了一个名为myRequiredDirective的自定义Angular指令。我想有条件地将它应用于输入控件,类似于使用[required]

的方式
<input class="form-control" [required]="false" />

但是,当我尝试使用myRequiredDirective执行类似操作时,出现错误:Can't bind to 'myRequiredDirective' since it isn't a known property of 'input'.

directive.ts

import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Validator, AbstractControl, Validators, NG_VALIDATORS, ValidatorFn } from '@angular/forms';

@Directive({
    selector: '[myRequiredDirective]',
    providers: [{ provide: NG_VALIDATORS, useExisting: MyRequiredDirective, multi: true }]
})

export class MyRequiredDirective implements Validator {

    private valFn = CustomValidator();

    validate(control: AbstractControl): { [key: string]: any } {
        return this.valFn(control);
    }

}

function CustomValidator(): ValidatorFn {

    return (control: AbstractControl): { [key: string]: any } => {
        let isValid = true;

        if (!control.value) {
            isValid = false;
        }

        if (control.value == 0) {
            // Set control invalid if value equals zero. Mainly used for drop downs where the default value is usually 0.
            isValid = false;
        }

        return isValid ? null : { 'required': 'message will come from validators.component.html' };
    };
}

有没有办法让我的自定义指令的行为与[required]类似?

编辑#1

我通过执行以下操作解决了Can't bind to 'myRequiredDirective' since it isn't a known property of 'input'.

export class MyRequiredDirective implements Validator {

    @Input() myRequiredDirective: boolean;

    private valFn = CustomValidator(this.myRequiredDirective); // this.myRequiredDirective is undefined

    validate(control: AbstractControl): { [key: string]: any } {
        return this.valFn(control);
    }

}

并在HTML模板中:

<input class="form-control" [myRequiredDirective]="false" />

但是,当我尝试将this.myRequiredDirective传递给CustomValidator时,Class未定义。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

=IF(IFERROR(FIND("CCC",E13,1),0),"Credible",IF(IFERROR(FIND("NC",E13,1),0),"Non Credible",IF(IFERROR(FIND("OP",E13,1),0),"OPEN",IF(IFERROR(FIND("COA",E13,1),0),"Credible","New"))))