FormControl或自定义指令

时间:2018-11-07 05:18:20

标签: angular2-forms

pageRangeValidator(control: FormControl) {
    if (control.value === '') {
      this.isValidRange = false;
    }
    if (control.value) {
      const selectedRange = control.value;
      const range = selectedRange.split('-');
      const startingPageIndex = +range[0];
      const endingPageIndex = +range[1];
      const totalPages = this.totalPages;
      if ((startingPageIndex > 0
        && startingPageIndex <= totalPages - 1
        && startingPageIndex < endingPageIndex
        && endingPageIndex > 0
        && endingPageIndex <= totalPages) || (startingPageIndex > 0
          && startingPageIndex <= totalPages
          && startingPageIndex === endingPageIndex
          && endingPageIndex > 0
          && endingPageIndex <= totalPages)) {
        this.isValidRange = true;
        this.pageRange.emit({
          validRange: this.isValidRange,
          preview: this.previewDone,
          value: control.value
        });
        return null;
      } else {
        this.isValidRange = false;
        this.pageRange.emit({
          validRange: this.isValidRange,
          preview: this.previewDone,
          value: control.value
        });
        return false;
      }
    }
    return null;
}

我创建了一个只接受特定范围内的值的表单控制元素,我使用了reactformsmodule和formcontrol并创建了它,但我想知道这是执行此操作的最佳方法还是为此使用定制指令

1 个答案:

答案 0 :(得分:0)

当然,在自定义指令中执行此操作会更优雅,特别是如果要多次使用它或希望使组件较小的话。该指令应能引起人们的注意并进行评估。