sandrooco
sandrooco

Reputation: 8726

Angular2 Form-validation with prefilled data

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]]
});

Upvotes: 9

Views: 10219

Answers (3)

n00dl3
n00dl3

Reputation: 21564

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>

Upvotes: 14

Gbacc
Gbacc

Reputation: 150

Your condition for the title input class is invalid

[class.validationError]="projectEditForm.controls.Name.invalid && (projectEditForm.controls.Description.dirty || submitted)"

It should be :

[class.validationError]="projectEditForm.controls.Title.invalid && (projectEditForm.controls.Title.dirty || submitted)"

Upvotes: 0

Igor Janković
Igor Janković

Reputation: 5532

Try to init the form group on http call success and then:

this.projectEditForm = this._fb.group({
    Title: [project.ProjectName, [<any>Validators.required, <any>Validators.minLength(5)]],
    Description: [project.Description, [<any>Validators.required]]
});

Upvotes: -1

Related Questions