【问题标题】:replace number on input number if it is too high directive如果输入数字太高,则替换输入数字上的数字指令
【发布时间】:2018-11-27 13:22:31
【问题描述】:

如果用户在当前年份之外输入年份,我希望在输入中替换数字。 示例:用户输入 2020,我想要一个将 2020 替换为当前年份(2018)的指令。

我的html代码:

<ion-item>
  <ion-label>year</ion-label>
  <ion-input type="number" [(ngModel)]="libro.year" name="data"></ion-input>
</ion-item>

【问题讨论】:

  • 为此使用反应形式。然后你可以为 formFields 自定义验证器

标签: angular typescript ionic-framework input numbers


【解决方案1】:

使用 directive 进行 DOM 操作。 指令获取它“附加”到的 DOM 元素,并通过某种特性对其进行增强。
使用Pipe 来操作数据。 pipe 获取数据作为输入,对其进行转换并以另一种方式输出此数据。

所以这是 Pipe 的完美用例

<ion-item>
      <ion-label>Anno</ion-label>
      <ion-input type="number" [ngModel]="libro.year|replace" (ngModelChange)="setYear($event)" name="data"></ion-input>
    </ion-item>
</ion-content>

管道

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'replace'
})
export class ReplacePipe implements PipeTransform {

  transform(value: any): any {
      if(parseInt(value)>2018)
        return '2018';
         return value;
  }

}

page.ts

setYear(event)
{
  this.year.libro=event;
}

LIVEDEMO

【讨论】:

    【解决方案2】:

    试试这个。

    在你的 component.ts 中

    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    public form: FormGroup;
    
    constructor(private fb: FormBuilder) { 
        this.form = this.fb.group({
          year: [2018, Validators.required],
        }, {validator: this.validateField('year')});
    }
    
    private validateField(controllerName: string) {
        return (group: FormGroup) => {
          const nameFiled = group.controls[controllerName];
          if (nameFiled.value > new Date().getFullYear()) {
            nameFiled.setValue(new Date().getFullYear());
            return nameFiled.setErrors({invalidYear: true});
          } else {
            return nameFiled.setErrors(null);
          }
        };
    }
    

    在您的模板中。

    <form [formGroup]="form">
      <ion-item>
          <ion-label>Anno</ion-label>
          <ion-input type="number" formControlName="year" name="data"></ion-input>
      </ion-item>
    </form>
    

    我为此创建了一个stackblitz。查看主页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多