Angular2 - 2.4.9 - 可重用组件上的自定义验证器

时间:2017-03-29 18:19:37

标签: angular

我正在尝试创建一个实现Validator的可重用组件。组件需要检查以确保数字是均匀的。我收到如下错误:

没有名称为'...'的表单控件的值访问器

以下是我的可重用组件:

import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl, Validator, NG_VALIDATORS } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: [NG_VALUE_ACCESSOR, NG_VALIDATORS],
    useExisting: forwardRef(() => EvenValidatorComponent),
    multi: true
};

@Component({
    moduleId: module.id,
    selector: 'even-validator',
    template: `<div>
<input type="number" [name]="name" [(ngModel)]="customValue" />
</div>`,
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class EvenValidatorComponent implements ControlValueAccessor, Validator {

    private innerValue: number;
    @Input() name: string;

    private onTouchedCallback: () => void = noop;
    private onChangeCallback: (_: any) => void = noop;

    validate(c: FormControl) {
        if (this.innerValue % 2 != 0) {
            return {
                notEvent: { valid: false }
            };
        }

        return null;
    }

    writeValue(value: number) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }
}

我的主要内容:

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'sandbox',
    template: `<form>
<even-validator name="evenValidator" [(ngModel)]="numericValue"></even-validator>
</form>`
})
export class SandboxComponent {
    protected  numericValue: number;
}

0 个答案:

没有答案