I have a form with two input fields (text). Creating from scratch (= no information) works great. As you can guess, maybe I want to change the values later.
The problem: When only changing the description for example (and leaving the title as is from the server), the title will be invalid. If I change the last char (Testproject to Testproject2) for example it works. What do I have to change?
Template:
<form [formGroup]="projectEditForm" novalidate>
<div [formGroup]="projectEditForm">
<label>Title</label>
<input type="text" [class.validationError]="projectEditForm.controls.Title.invalid && (projectEditForm.controls.Title.dirty || submitted)"
value="{{ (project | async)?.ProjectName }}" formControlName="Title">
<label>Description</label>
<textarea [class.validationError]="projectEditForm.controls.Description.invalid && (projectEditForm.controls.Description.dirty || submitted)"
value="{{ (project | async)?.Description }}" formControlName="Description"></textarea>
</div>
</form>
Form model:
this.projectEditForm = this._fb.group({
Title: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
Description: ['', [<any>Validators.required]]
});
Your problem comes from the fact that you are not using the FormControl
correctly. You should not bind to the value
attribute of the input
tag because it's FormControl
's job.
When binding to the value
attribute, you are writing to the dom without notifying the FormControl
that something has changed.
You should set the value dynamically using the FormControl
instead. When you receive the data from http, you just need to call this :
this.projectEditForm.get("controlName").setValue(randomValueFromSomewhere);
in your template (note that I removed the classes to be more concise):
<div [formGroup]="projectEditForm">
<label>Title</label>
<input type="text" formControlName="Title">
<label>Description</label>
<textarea formControlName="Description"></textarea>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With