如何在触摸后验证自定义角形控件?

时间:2017-10-19 17:44:31

标签: angular

我有一个自定义表单控件,并且验证排序似乎正常,但触摸控件后未调用validate方法。在我简单的自定义表单控件中,我希望能够在触摸控件时进行验证,而不仅仅是在其值发生变化后进行验证。

我怎样才能实现这一目标?或者有更好的方法来进行初始验证吗?

这是一个带有示例组件(https://plnkr.co/edit/qAWDsH?p=preview)的插件。我想在触摸后自定义组件的验证失败。

这是我的自定义控件:

@Component({
  selector: 'my-custom-control',
  template: `

      <input type="text"
            style="color:red;"
            placeholder="Valid with odd # of characters"
            #input="ngModel"
            [(ngModel)]="text"
            (change)="onInputChanged($event)"
            (blur)="onBlur()"
            (focus)="onFocus()" 
      >

  `,
  providers: [
    CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR,
    CUSTOM_CONTROL_VALIDATOR
  ] 
})
export class MyCustomControl implements ControlValueAccessor, OnChanges, OnInit, Validator {

  @Input() text: string;
  @Input() placeholder: string; 
  @Input() required: any;

  constructor() {

  }

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

  onBlur() {
    console.log("custom control blur");
    this.onTouchedCallback();
  }

  onFocus() {
    console.log("custom control focus");
    this.onTouchedCallback();
  } 

  onInputChanged() {
    console.log("value changing");
    this.onChangeCallback(this.text);
  }

  //From ControlValueAccessor interface
  writeValue(value: string) {
    this.text = value;
  }

  //From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  //From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  ngOnInit() {}
  ngOnChanges() {
    this.onChangeCallback(this.text);
  } 

  // From Validator interface
  validate (c: FormControl) {
    console.log('validating');
    if (this.text.length % 2) 
      return null;

    return { 
      customError: {
        message: "This is not valid",

      }
    }
  }  

}

1 个答案:

答案 0 :(得分:0)

试试这样:

你可以像这样添加keyup事件

TextArea

在compoent.ts中

CssLayout