2016-11-26 64 views
0

問題:我想提交一份帶有原始數據的表單,但驗證程序不允許我這樣做,因爲表單無效。用原始數據發送Angular2表格

我試圖用驅動方式的數據發送形式,表單生成器,我想送是一個模式裏面的數據。該模式的目的是使用戶可以編輯一些數據,對模態的輸入字段都充滿了以前的數據,這就是爲什麼我並不需要檢查,如果用戶更改值,但是我仍然需要檢查如果這些字段不是空的。

忽略選擇器是在模態的底部。

[模態的屏幕截圖] [1] [1]:https://i.stack.imgur.com/Q1GU4.png

窗體生成代碼

this.editProblemForm = this._formBuilder.group({ 
    'problemDetails': this._formBuilder.group({ 
    'engDescription': ['', Validators.required], 
    'spnDescription': ['', Validators.required] 
    }) 
}); 

模態代碼,其中值被檢索,在所述摘錄的底部是一個按鈕,是當表單是無效的禁用,的問題是,當用戶打開的所有信息已經被填滿,使按鍵不應該被禁用的模式,但它是。

<!-- Descriptions --> 
 
<div class="row margin-top20"> 
 
    <div class="input-group margin-top20"> 
 
    <label for="desc_engEdit">Problem description: English</label> 
 
    <textarea id="desc_engEdit" rows="6" formControlName="engDescription" [value]="descriptionEng" 
 
       class="form-control white-space"></textarea> 
 
    </div> 
 
</div> 
 
<div class="row margin-top20 margin-bottom20"> 
 
    <div class="input-group margin-top20"> 
 
    <label for="desc_spnEdit">Problem description: Spanish</label> 
 
    <textarea id="desc_spnEdit" rows="6" formControlName="spnDescription" [value]="descriptionSpn" 
 
       class="form-control white-space"></textarea> 
 
    </div> 
 
</div> 
 

 
<button [disabled]="!editProblemForm.valid" type="submit" class="btn btn-primary">Save changes 
 
        </button>

解決方案使用@silentsod方法

updateFormValues(){ 

let formObject : any; 
    formObject = this.editProblemForm.controls['problemDetails']; 
    formObject.controls['engDescription'].setValue(this.descriptionEng); 
    formObject.controls['spnDescription'].setValue(this.descriptionSpn); 
} 

謝謝!

+0

你能告訴你如何設置這些值? – silentsod

+0

@silentsod我剛剛更新了問題,謝謝 –

回答

1

的問題是,與活性形式(模型驅動的),你需要調用setValue正確更新控制值。否則,它會認爲該表單是空的,並且您所需的驗證器未被滿足。

假設你已經在你被送入模態,什麼控制再打開的時候,你的模態分量打字稿

onOpen() { //or however you've named it/arguments you have 
    this.editProblemForm.controls['problemDetails'].controls['engDescription'].setValue(descriptionEng); //wherever you got that from 
    this.editProblemForm.controls['problemDetails'].controls['spnDescription'].setValue(descriptionSpn); //wherever you got that from 
} 

順便說一句,你也不應該使用[disabled]而是編程在控件上調用.disable().enable()。在控制檯日誌中會有一條警告消息。

+0

它的工作!我只需要首先將表單對象保存在變量中,因爲TypeScript不允許我在一行中完成所有操作。謝謝! –