Angular prefilled form data becomes null when submitting

Viewed 489

I have created an Angular form to update the user details. The fields values of the form are filled by the user details fetched from the backend when the form loads. If the user wishes to update any field they can update and submit the form. But the field values of the fields which user didn't change are set as null even though those fields are initialized at the beginning. Can someone please explain how to get the prefilled unchanged field values when submitting the form? The HTML file is this,

<app-navbar></app-navbar>
  <div class="container">
  <form [formGroup]="profileForm" style="margin-top: 60px;" disabled="true" (ngSubmit)="onSubmit()">
    <input type="file" id="file" (change)="onFileSelected($event)" accept="image\jpeg" formControlName="profPic">
    <div class="row">
      <!--Profile Picture-->
      <div class="col-12 col-md-4 d-flex justify-content-center">
          <label for="file">
            <a (mouseenter)="hoverIdx = 1"
               (mouseleave)="hoverIdx = -1"
               id="overlay">
             <span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== 1 }"
                  class="rounded-circle">
                  <fa-icon [icon]="cameraIcon" class="icon"></fa-icon>
             </span>
              <img
                [src]="profPic"
                class="rounded-circle"
                width="300"
                height="300"
              />
           </a>
          </label>
          <div class="col-md-2 align-self-end ml-auto p-2" id="deleteIcon">
               <fa-icon [icon]="deleteIcon"></fa-icon>
          </div>
      </div>
      <div class="col-12 col-md-8">
      <div class="card" style="margin-bottom: 20px;">
        <div class="card-body" >
                  <!---Intro-->
        <div class="row" style="font-size: 60px;">
          <div class="col-12">Hi, {{ fNme }}</div>
        </div>
        <!--first name & last name-->
        <div class="row" style="margin-top: 10px;">
          <div class="col-12 col-md-6">
            <mat-form-field appearance="outline">
              <input formControlName="fName"
                     matInput placeholder="First Name"
                     [value]="fNme"
                     (change)="fNmeChnge = true"/>
            </mat-form-field>
          </div>
          <div class="col-12 col-md-6">
            <mat-form-field appearance="outline">
              <input formControlName="lName"
                     matInput placeholder="Last Name"
                     [value]="lNme"
                     (change)="lNmeChnge = true" />
            </mat-form-field>
          </div>
        </div>
        <!--row-->
        <!-- email & country-->
        <div class="row" style="margin-bottom: 25px;">
          <div class="col-12 col-md-6">
            <mat-form-field appearance="outline">
              <input formControlName="email"
                     matInput placeholder="Email"
                     [value]="email"
                     (change)="emailChnge = true"/>
            </mat-form-field>
          </div>
          <div class="col-12 col-md-6">
            <mat-form-field appearance="outline" >
              <input formControlName="country"
                     matInput placeholder="Country"
                     [value]="country"
                     (change)="countryChnge = true"/>
            </mat-form-field>
          </div>
        </div>
        <!--row-->
        </div>
      </div>
         <button type="button" class="btn btn-primary float-right" style="margin-left:10px" type="submit">Save</button>
         <button type="button" class="btn btn-outline-primary float-right" (click)="cancel()">Cancel</button>
      </div><!--col-md-8-->
    </div><!--row-->
  </form>
</div><!--container-->

The component file is this,

import { User } from './../shared/user.model';
import { F_NAME, L_NAME, AUTHENTICATED_USER, PROF_PIC, BASE64URL } from './../../app.constants';
import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AuthenticationService } from '../service/authentication.service';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '@angular/material/dialog';
import { DialogOverviewExampleDialog } from './dialog';
import { faCamera, faTrashAlt } from '@fortawesome/free-solid-svg-icons';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  user: User;
  cameraIcon = faCamera;
  deleteIcon = faTrashAlt;
  profPic: any;
  profileForm: FormGroup;
  email: string;
  fNme: string;
  lNme: string;
  country: any;
  selectedFile: File = null;
  base64Data: any;
  fNmeChnge: any;
  lNmeChnge: any;
  countryChnge: any;
  emailChnge: any;
  title = 'Profile';

  constructor(
              private service: AuthenticationService,
              public dialog: MatDialog,
              private sanitizer: DomSanitizer
  ) {
  }

  ngOnInit() {
     this.email = sessionStorage.getItem(AUTHENTICATED_USER);
     this.profileForm = new FormGroup({
      fName: new FormControl(null, [Validators.required]),
      lName: new FormControl(null, Validators.required),
      email: new FormControl(null, [Validators.required, Validators.email]),
      country: new FormControl(null, Validators.required)
    });
     this.service.getUser(this.email)
      .subscribe(res => {
          this.fNme = res.fNme;
          this.lNme = res.lNme;
          this.country = res.country;
          this.profPic = BASE64URL + res.profPic ;
      });

  }

openDialog(): void {
    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '500px'
    });
  }

onFileSelected(event){
    this.selectedFile = event.target.files[0] as File;
    const reader = new FileReader();
    reader.onload = e => this.profPic = reader.result;
    reader.readAsDataURL(this.selectedFile);
  }

onSubmit() {
    const fd = new FormData();
    fd.append('file', this.selectedFile);
    this.service.uploadImage(fd, this.email);
    this.user = new User(this.profileForm.get('fName').value,
                         this.profileForm.get('lName').value,
                         this.profileForm.get('country').value,
                         this.profileForm.get('email').value);
    console.log(this.user);
    this.service.updateProfile(this.user, this.email);
                              // .subscribe(res => {
                              //   this.fNme = res.fNme;
                              //   this.lNme = res.lNme;
                              //   this.country = res.country;
                              //   this.profPic = BASE64URL + res.profPic ;
                              // });
    this.ngOnInit();
  }

I gets the user data from the server via these codes,

 uploadImage(file: FormData, email: string) {
    this.http.put<any>(`${API_URL}/profile-picture/${email}`, file)
    .subscribe(res => {console.log(res); });
  }

  updateProfile(user: User, email: string) {
     this.http.put<any>(`${API_URL}/profile/${email}`, user).subscribe();
  }

  getUser(email: string) {
     return this.http.get<any>(`${API_URL}/user/${email}`);
  }
0 Answers
Related