2017-10-09 63 views
1

我試圖在角度無效表單上設置條件表單驗證並需要一些幫助。角度無效表單的條件表單驗證

我有其中用戶將他們的實體類型到個人或商業

<select formControlName="entity"> 
    <option [value]="individual">Individual</option> 
    <option [value]="business">Business</option> 
</select> 

然後我有顯示或隱藏基於被選擇什麼實體形式輸入的表單控件:

<div *ngIf="myForm.controls.entity.value == individual> 
    <input formControlName="fullName" /> 
</div> 

<div *ngIf="myForm.controls.entity.value == business> 
    <input formControlName="businessName" /> 
</div> 

只有選擇了相應的實體,我如何才能使兩個輸入都是必需的?

+0

的可能的複製[角2:在某些條件應用Validator.required驗證](HTTPS://計算器.com/questions/42238639/angular-2-apply-validator-required-validation-on-some-condition) – JayChase

回答

4

您可以使用屬性[formControl] = 「name_of_your_input_control」 假設這個網站是一個formGroup元素

<div [hidden]="isBusiness"> 
    <input [formControl]="fullName" /> 
</div> 

<div [hidden]="!isBusiness"> 
    <input [formControl]="businessName" /> 
</div> 

內的TS類:

創建後您的形式補充一點:

isBusiness:boolean = false; 
//... 
this.nameOfYourForm.valueChanges.subscribe((newForm) => { 
    this.isBusiness = (newForm.controls.entity.value == 'business'); 
    if(this.isbusiness){ 
     this.nameOfYourForm.controls.fullName.setValidators(/*your new validation here*/); 
      //set the validations to null for the other input 
    }else{  
      this.nameOfYourForm.controls.businessName.setValidators(/*your new validation here*/); 
      //set the validations to null for the other input 
    } 
}); 

請注意,我已將* ngIf更改爲[hidden],因爲* ngIf將完全從您的模板中刪除控件,其中[hidden]只會應用顯示沒有。

您也可以在特定的控件上添加更改偵聽器,而不是整個表單,但這個想法是相同的。

+0

或者您可以在運行時定義您的控件: isBusiness:boolean = false; //... this.nameOfYourForm.valueChanges.subscribe((newForm) => { this.isBusiness = (newForm.controls.entity.value == 'business'); if(this.isbusiness){ this.nameOfYourForm.registerControl('yourControl', new FormControl('', [Validators])); }else{ this.nameOfYourForm.removeControl('yourControl'); })

1

我有一個其他版本:

HTML

<select #select formControlName="entity"> 
    <option [ngValue]="Individual">Individual</option> 
    <option [ngValue]="Business">Business</option> 
</select> 
<br> 
<div *ngIf="select.value[0] === '0'"> 
    <input #input [required]="select.value[0] === '0'" formControlName="fullName" /> 
    <span *ngIf="!myForm.get('fullName').valid">Invalid</span> 
</div> 

DEMO