提交时有角预填表格数据为空

时间:2019-10-26 15:17:37

标签: angular8 angular-forms

我创建了一个Angular表单来更新用户详细信息。表单的字段值由表单加载时从后端获取的用户详细信息填充。如果用户希望更新任何字段,则可以更新并提交表单。但是,即使这些字段在开始时已初始化,但用户未更改的字段的字段值仍设置为null。有人可以解释提交表单时如何获取预填充的不变字段值吗? HTML文件是这个,

<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-->

组件文件是这个

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

我通过这些代码从服务器获取用户数据,

 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 个答案:

没有答案