1

In my Angular project I have a form to update user informations. My UserAccount class is :

import { Useraccounttype } from './../model/useraccounttype.model';
import { Gender } from './Gender.interface';
export interface UserAccount{
    // User infos
    id?: number;
    firstName: string;
    lastName: string;
    mail: string;
    genderId: number;
    gender?: Gender;
    password: string;
    userName: string;
    login: string;
    useraccountTypeId: number;
    userAccountType?: Useraccounttype;
    name?: string;
    commercialmail?: string;
    phone?: string;
    vatnumber?: string;
}

For example if I change only the firstname field. When I submit my form and want to read fields to update the db with the following method:

private executeUserAccountUpdate = (userForm) => {
    if (this.myForm.valid) {
      const user: UserAccount = {
        id: this.user.id,
        firstName: this.f.firstname.value,
        lastName: this.f.lastname.value,
        mail: this.f.mail.value,
        genderId: this.f.gender.value,
        password: this.f.password.value,
        userName: this.f.username.value,
        login: this.f.login.value,
        useraccountTypeId: this.f.useraccountType.value,
      }

      let apiUserAccount: string = environment.apiAddress + 'UserAccount/' + this.user.id;
      this.repository.update(apiUserAccount, user)
      .subscribe(response => {
        $('#successModal').modal();
      },
      (error =>{
        this.errorHandler.handleError(error);
        this.errorMessage = this.errorHandler.errorMessage;
      })
      )
    }
    else {
      console.log('Is not Valid');
    }
  }

In my User object, the field firstname has value but the others are empty ('').

The Html part:

<div class="container rounded bg-white mt-5 mb-5">
    <form [formGroup]="myForm" autocomplete="off" novalidate (ngSubmit)="updateUserAccount(myForm.value)">
    <div class="row">
        <div class="col-md-3 border-right">
            <div class="d-flex flex-column align-items-center text-center p-3 py-5">
                <img class="rounded-circle mt-5" width="150px" src="https://st3.depositphotos.com/15648834/17930/v/600/depositphotos_179308454-stock-illustration-unknown-person-silhouette-glasses-profile.jpg">
                    <span class="font-weight-bold">{{user?.firstName}} {{user?.lastName}}</span>
                    <span class="text-black-50">{{user?.mail}}</span>
                    <span></span>
                </div>
        </div>
        <div class="col-md-5 border-right">
            <div class="p-3 py-5">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4 class="text-right color-secondary">Profile</h4>
                </div>
                <div class="row mt-2">
                    <div class="col-md-12">
                        <app-gender name="gender" id="gender" [formGroup]="myForm" [selectedValue]="user?.gender?.description">
                            <em *ngIf="validateControl('gender') && hasError('gender', 'required')">Sélectionnez un genre</em>
                        </app-gender>      
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-6"><label class="labels">Nom</label><input type="text" class="form-control" formControlName="lastname" placeholder="Nom" value="{{user?.firstName}}" >
                        <em *ngIf="validateControl('lastname') && hasError('lastname', 'required')">Nom obligatoire</em>
                    </div>
                    <div class="col-md-6"><label class="labels">Prénom</label><input type="text" class="form-control"  formControlName="firstname" value="{{user?.lastName}}" placeholder="Prénom" >
                        <em *ngIf="validateControl('firstname') && hasError('firstname', 'required')">Prénom obligatoire</em>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12 mt-2"><label class="labels">Nom d'utilisateur</label><input type="text" class="form-control" formControlName="username" placeholder="Nom d'utilisateur" value="{{user?.userName}}" >
                        <em *ngIf="validateControl('username') && hasError('username', 'required')">Nom d'utiliateur obligatoire</em>
                    </div>
                    <div class="col-md-12 mt-2"><label class="labels">Mail</label><input type="text" class="form-control" formControlName="mail" placeholder="Mail" value="{{user?.mail}}" >
                        <em *ngIf="validateControl('mail') && hasError('mail', 'required')">Mail obligatoire</em>
                    </div>
                    <div class="col-md-12 mt-2"><label class="labels">Login</label><input type="text" class="form-control" formControlName="login" placeholder="Login" value="{{user?.login}}" >
                        <em *ngIf="validateControl('login') && hasError('login', 'required')">Login obligatoire</em>
                    </div>
                    <div class="col-md-12 mt-2"><label class="labels">Password</label><input type="text" class="form-control" formControlName="password" placeholder="Password" value="{{user?.password}}" >
                        <em *ngIf="validateControl('password') && hasError('password', 'required')">Mot de passe obligatoire</em>
                    </div>
                    <!-- <div class="col-md-12"><label class="labels">Type de compte</label><input type="text" class="form-control" formControlName="useraccountType" placeholder="enter address line 2" value="{{user?.userAccountType?.shortDescription}}" ></div> -->

                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <label class="labels">Type d'utilisateur</label>
                            <app-useraccount-type name="useraccountType" id="useraccountType" [formGroup]="myForm" [selectedType]="user?.userAccountType?.shortDescription">
                                <em *ngIf="validateControl('useraccountType') && hasError('useraccountType', 'required')">Mot de passe obligatoire</em> 
                            </app-useraccount-type>      
                        </div>

                    </div>
                <div class="row mt-3">
                    <div class="col-md-6"><label class="labels">Country</label><input type="text" class="form-control" placeholder="country" value=""></div>
                    <div class="col-md-6"><label class="labels">State/Region</label><input type="text" class="form-control" value="" placeholder="state"></div>
                </div>
                <div class="mt-5 text-center"><button class="btn btn-primary profile-button" type="submit">Sauvegarder</button></div>
            </div>
        </div>
        <div class="col-md-4">
            
        </div>
    </div>
    </form>
</div>

I don't understand why and I don't know how to solve this problem.

Who can explain it and give me a solution to update the full object.

Thanks for your help.

Paintbox
  • 359
  • 5
  • 12
  • Depends on how you initialize your form and how you handle the update on your api. – Ric Sep 20 '21 at 09:06
  • @Ric thanks for your answer. I just do that ```get f() { return this.myForm.controls; } ``` to read my form fields. Is there anything else I can do? – Paintbox Sep 20 '21 at 09:17
  • can you update the question with the html and also how you have defined `myForm` – Owen Kelvin Sep 20 '21 at 09:19
  • @Owen Kelvin it's done. For information, the problem is before sending request to my Web Api. – Paintbox Sep 20 '21 at 09:26
  • Ok I found a solution her [link](https://stackoverflow.com/questions/55662486/angular-reactive-form-returns-empty-values-when-fields-are-untouched). At the begining, I use the wrong way to populate the form. So, the non updated fields are empty. – Paintbox Sep 20 '21 at 10:21

1 Answers1

0

This is the solution of my problem. I found it here link

The first things to do is populate the form with datas by using patchValue(). So when I load datas, I must do this :

 public loadUserDetails = () => {
    let id: string = this.activeRoute.snapshot.params['id'];
    let apiUser: string = environment.apiAddress + 'UserAccount' + '/' + id;

    this.repository.getData(apiUser).pipe()
      .subscribe(response => {
        this.myForm.patchValue({
          firstname: (<UserAccount>response).firstName,
          lastname: (<UserAccount>response).lastName,
          mail: (<UserAccount>response).mail,
          Gender: (<UserAccount>response).genderId,
          password: (<UserAccount>response).password,
          username: (<UserAccount>response).userName,
          login: (<UserAccount>response).login,
          useraccountType: (<UserAccount>response).useraccountTypeId,
        })
      },
        (error) => {
          this.errorHandler.handleError(error);
          this.errorMessage = this.errorHandler.errorMessage;
        })
  }

And when I submit my form, I need to do this to get form datas :

public updateUserAccount= () =>{
    const userAccountForm = this.myForm.value

    if(this.myForm.valid){
      this.executeUserAccountUpdate(userAccountForm)
    }
    else{
      console.log('Is not Valid');
    }
  }

Hoping that can help others. Thanks to all of you for your help.

Paintbox
  • 359
  • 5
  • 12