在@Input更改时触发自定义表单控件验证

时间:2018-01-09 08:16:10

标签: angular typescript

我有一个带有一个输入的简单自定义表单控件:

const NGX_HELLO_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => HelloComponent),
    multi: true
};

const NGX_HELLO_VALIDATORS = {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => HelloComponent),
    multi: true
};

@Component({
    selector: 'hello',
    template: `<p>Value in custom form control: {{value}}</p>`,
    providers: [NGX_HELLO_VALUE_ACCESSOR, NGX_HELLO_VALIDATORS]
})
export class HelloComponent implements OnChanges, ControlValueAccessor, Validator  {

    @Input() maxLength: number;

    value: string;
    onChangeCb: (_: any) => void = () => { };
    onTouchedCb: () => void = () => { };

    ngOnChanges(changes: SimpleChanges): void {
        //trigger validation
    }

    writeValue(value: any): void {
        this.value = value;
    }

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

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

    validate(control: FormControl): ValidationErrors {
        if(this.value && this.value.length > this.maxLength) {
            return {
                tooLong: this.maxLength
            };
        }
        return null;
    }
}

工作正常。每当值发生变化时,角度调用都会生效并验证控件。问题是如何在@Input maxLength更改后运行验证?

我创建了stackblitz示例来玩。

1 个答案:

答案 0 :(得分:2)

 ngOnChanges(changes: SimpleChanges): void {
    //trigger validation
    this.onChangeCb(this.value);
  }

诀窍,似乎对价值变化进行角度重新运行验证。

Forked stackblitz