Problem: I want to submit a form with pristine data, but the Validators does not allow me to do that, because the form is invalid.
I'm trying to send a form using data driven approach, with Form Builder, the data that I want to send is inside a modal. The purpose of the modal is that the user can edit some data, the input fields on the modal are filled with the previous data, that is why I don't need to check if the user change the value, however I still need to check if the fields are not empty.
Ignore the selector that is on the bottom of the modal.
[Screenshot of modal][1] [1]: https://i.stack.imgur.com/Q1GU4.png
Form Builder code
this.editProblemForm = this._formBuilder.group({
'problemDetails': this._formBuilder.group({
'engDescription': ['', Validators.required],
'spnDescription': ['', Validators.required]
})
});
Modal code, where values are retrieved, at the bottom of the snippet is a button that is disabled when the form is not valid, the problem is that when the user opens the modal all the information is already filled, so the button should not be disabled, but it is.
<!-- 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>
Solution using @silentsod approach
updateFormValues(){
let formObject : any;
formObject = this.editProblemForm.controls['problemDetails'];
formObject.controls['engDescription'].setValue(this.descriptionEng);
formObject.controls['spnDescription'].setValue(this.descriptionSpn);
}
Thanks!!
答案 0 :(得分:1)
问题在于,使用Reactive Forms(模型驱动),您需要调用setValue
来正确更新控件值。否则,它会认为表单是空的,并且您的所需验证器未得到满足。
假设您可以控制发送到模态的内容,那么在打开时,在模态组件TypeScript中:
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()
。您的控制台日志中会有一条警告消息。