2017-10-11 78 views
1

我試圖動態驗證在角4角ReactiveForms - 動態設置驗證行爲異常

我的問題添加到ReactiveForm是,SetValidators()函數的行爲不知何故意外。

我想有這種行爲:

輸入字段可以是空的,但IF用戶想要輸入的東西,輸入值必須是至少4個字符長。

我不打算解釋它現在的表現如何,因爲我真的不知道它是如何表現的。請致電this plunker。這很簡單,證明我的問題。

對我的問題:我在這裏做錯了什麼?這是正確的方法嗎?我錯過了什麼嗎?要麼在邏輯中,要麼在HTML中?

回答

3

ValueChanges訂閱的表單控件將導致此錯誤Maximum call stack size exceeded,所以最好使用其事件控制輸入中的更改(例如,鍵入)。

並且在設置新的驗證器應用它們之後不要忘記使用updateValueAndValidity

這是您的組件的新代碼,它的工作原理現在好:)

//our root app component 
import {Component, NgModule, VERSION} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms"; 
import {FormsModule, ReactiveFormsModule} from "@angular/forms"; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <form [formGroup]="userForm"> 
     <section> 
      <div> 
      <label>username</label> 
      <input (keyup)="inputValueChanged($event)" formControlName="username" type="text"> 
      </div> 
      <button [disabled]="disableSaveButton()">Save</button> 
     </section> 
     </form> 
    </div> 
    `, 
}) 
export class App implements OnInit { 

    userForm: formGroup 

    constructor(private formBuilder: FormBuilder) { 
    } 

    disableSaveButton(): boolean { 
    console.log("is valid:", this.userForm.controls["username"].valid); 
    return this.userForm.controls["username"].invalid 
    } 

    ngOnInit(): void { 
    this.userForm = this.formBuilder.group({ 
     username: '', 
    }); 
    } 

    inputValueChanged(event){ 
    let value = this.userForm.controls["username"].value; 
    if (value.length > 0) { 
      console.log("should be invalid if < 4") 
      this.userForm.controls["username"].setValidators([Validators.required, Validators.minLength(4)]); 

     } else { 
      console.log("should be valid") 
      this.userForm.controls["username"].setValidators([]); 
     } 
     this.userForm.controls["username"].updateValueAndValidity(); 

    } 


} 

@NgModule({ 
    imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

希望它有助於ü:)

+0

謝謝你,我用'updateValueAndValidity'試了一下,但正如你所提到的,得到了​​'最大調用堆棧大小超過錯誤'。但按照預定的方式進行。 – RagnarLothbrok

2

只需在窗體的聲明中加入驗證,以便它驗證長度,但不是必需的,並刪除您訂閱valueChanges因爲它redondant:

this.userForm = this.formBuilder.group({ 
    username: ['', Validators.minLength(4)], 
}); 

我修改your plunker

+0

好吧,那很簡單,呵呵..謝謝+1。我接受Medi_Ali_Rachid,因爲它回答了我的問題。 – RagnarLothbrok

0

我建議作出的CustomValidator和修改本的CustomValidator

ngOnInit(): void { 
    this.userForm = this.formBuilder.group({ 
     username: ['',this.customValidator], 
    }); 
} 

customValidator(input:Formcontrol) 
{ 
    let condition:boolean 
    ...change condition depending some variables... 
    return condition?null:{errorDesc:"Not Valid"} 

}