Jason
Jason

Reputation: 1059

Angular Reactive Edit Form Pre-Populated Fields still triggers "required" error

I use the same Reactive Form in Angular for adding and editing.

this.form = fb.group({
            username:['',Validators.required ],
            email:['',Validators.required]            
        })                

I use the required validator and it works well for 'add' when I don't input anything into the field and a warning message appears.

<form [formGroup]="form" (ngSubmit)="submit()">
    <div class="form-group">
        <label for="username">Username</label>
        <input [(ngModel)]="user.name" type="text" class="form-control" 
formControlName="username" value={{(singleUser|async)?.name}}>
        <div *ngIf="form.controls.username.touched && 
!form.controls.username.valid" class="alert alert-danger">
            Username is required
        </div>  
    </div>

However, for edit, when I show the form with populated existing values, the required error is triggered when i touched the field and don't make any changes to the existing value. Thus, the warning message also appears.

But in this case, it shouldn't show the warning message since there is an existing value only that I have not made any changes to it.

How can I code it such a way that for edit, the required error is not triggered for pre-populated existing values?

Upvotes: 2

Views: 4311

Answers (1)

Christian
Christian

Reputation: 2831

You're setting the form values incorrectly. When using Reactive Forms, you're supposed to do things programatically instead of in the template. That means you need to remove value="...", and in your component, once you've fetched the data you can do:

this.form.setValue(singleUser)

Or to set the value of a single form control:

this.form.get('username').setValue(singleUser.username)

You might run into errors with .setValue when setting the value of the entire form because that method expects an object with the exact same properties as the one defined for your FormGroup. So you'd have to always set the value with an object with the username and email properties. If it's possible that the object won't have all the properties use the patchValue method instead. That will simply set the values of any matching properties and ignore any extra ones, like for example if the object also has an id property.

You should also remove the stuff you're doing with ngModel. That belongs to the FormsModule, and it's a bad practice to mix them. You already have the value of the form

this.form.value

Upvotes: 3

Related Questions