2017-10-16 96 views
0

據我所知(可能不是很好,因爲我今天才開始看這個)there is are validators built in to Angular將檢查<input type='number'>的最大值和最小值。
我試圖讓這個工作在我正在構建的應用程序中,但只有在輸入完全爲空時它纔會失效。其他值驗證,即使我的最小/最大範圍之外的數字。用於輸入的角度最小值和最大值驗證器[type ='number']

I tried to replicate it in a plunk but here it is just always valid。我在漫長的一天結束 - 任何人都可以只是解釋什麼,我必須做的,使場在我普拉克是有效與當超出這個範圍的5-10和無效值,空或其他只是...無效。

+0

你永遠不會在任何地方使用驗證器。它們只會在默認情況下應用於角度爲5的模板驅動窗體。 –

+0

看起來最小/最大支持被刪除,因爲添加它是一個突破性更改。看到這個:https://github.com/angular/angular/issues/17491和這個:https://github.com/angular/angular/issues/18830 – DeborahK

回答

0

我強烈建議你使用活性形式代替。
With 反應式表格您的業務邏輯保留在component.ts代碼中,使您的模板更加清晰和易於推理。

WorkingExample (based on your original plunk)


說明:

component.ts

myForm = new FormGroup({}) // Instantiating our form 

constructor(private fb: FormBuilder){ // Injecting the ReactiveForms FormBuilder. 
    this.myForm = fb.group({ 
    // Adding the "myNum" input to our FormGroup along with its min-max Validators. 
    'myNum': ['', [Validators.min(5), Validators.max(10)]] 
    }) 
} 

component.html - 模板

<form [formGroup]="myForm"> <!-- Binding myForm to the form in the template --> 

    <label for="myNum">Some Val</label> 
    <!-- formControlName binds our myNum field declared in the ts code. --> 
    <input type='number' id="myNum" formControlName="myNum"> 

</form> 
+1

我認爲這將是矯枉過正,潛入反應(從未看過在他們之前)這樣一個小表格,但實際上(在我看來)比基於模板更直觀。所以歡迎讓我朝着正確的方向前進。 – popClingwrap

0

我有一個自定義編號範圍驗證此:https://github.com/DeborahK/MovieHunter/tree/master/src/app/shared

它基本上是這樣的:

static range(min: number, max: number): ValidatorFn { 
    return (c: AbstractControl): { [key: string]: boolean } | null => { 
     if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) { 
      return { 'range': true }; 
     } 
     return null; 
    }; 
} 
相關問題