尝试创建更新函数时,角度中的表单字段不显示已填充的数据

发布于 2025-01-10 21:24:51 字数 5735 浏览 0 评论 0原文

我正在创建一个可以执行 CRUD 操作的 MEAN 应用程序,但是当我创建更新函数时,表单字段不会填充要更新的现有数据。 HTML:

<button
              mat-button
              color="basic"
              [routerLink]="['/moc-report', mocreport._id]"
            >
              Update Status
            </button>

这是按钮,但要更新,但表单不包含更新所需的数据: 包含要更新的数据的表单的 HTML:

<div class="container">
  <!--Navbar-->
  <mat-toolbar color="primary">
    <div class="centerNavBar">
      <a mat-button href="fa-dashboard">Back</a>
      &nbsp;
      <span class="headSpacer">Damage Assessment Tool</span>
      &nbsp;
      <a mat-button href="">Logout</a>
    </div>
  </mat-toolbar>
</div>

<div>
  <mat-sidenav-container class="MainContainter">
    <!--SideNav-->
    <mat-sidenav mode="side" opened>
      <div>
        <a mat-button href="">Message Board</a>
      </div>
    </mat-sidenav>
    <mat-sidenav-content class="MainContent">
      <mat-card>
        <mat-card-header class="sect">Create report:</mat-card-header>
        <br /><br />
        <mat-card-content class="centerAlign">
          <!--Div for form-->
          <div>
            <form [formGroup]="form" (submit)="addMOCForm()">
              <mat-form-field class="formwidth">
                <input
                  matInput
                  class="form-control"
                  formControlName="MoCReportDateTime"
                  type="Date"
                  required
                />
              </mat-form-field>
              <br />
              <mat-form-field>
                <mat-label>Comment</mat-label>
                <input
                  placeholder="--"
                  matInput
                  formControlName="MoCDescription"
                  class="form-control"
                  type="string"
                  required
                />
              </mat-form-field>
              <br />
              <mat-form-field>
                <mat-label>Facility In Question</mat-label>
                <input
                  placeholder="--"
                  matInput
                  formControlName="facilityName"
                  class="form-control"
                  type="string"
                  required
                />
              </mat-form-field>
              <mat-card class="centerAlign">
                <mat-card-actions>
                  <!--Div for buttons-->
                  <div>
                    <input
                      style="display: none"
                      #ImageInput
                      type="file"
                      (change)="onFileSelected($event)"
                    />

                    <button
                      mat-raised-button
                      type="button"
                      (click)="ImageInput.click()"
                    >
                      Upload Images
                    </button>
                    &nbsp;
                    <button mat-raised-button color="primary" type="submit">
                      Add
                    </button>
                  </div>
                </mat-card-actions>
              </mat-card>
            </form>
          </div>
        </mat-card-content>
      </mat-card>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

TS:

import { AfterViewInit, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {
  FormBuilder,
  FormGroup,
  FormControl,
} from '@angular/forms';

import { HttpClient } from '@angular/common/http';

import { MOCReportService } from 'src/app/service/mocreport.service';

@Component({
  selector: 'app-moc-report',
  templateUrl: './moc-report.component.html',
  styleUrls: ['./moc-report.component.css'],
})
export class MocReportComponent implements OnInit {
  
  image: any;
  Image = [];
  imageData: any;

  constructor(
    private mocreportservice: MOCReportService,
    //private mapService: MocMapService,
    private router: Router,
    private fb: FormBuilder,
    private http: HttpClient
  ) {}
  form = new FormGroup({
    facilityName: new FormControl(''),
    MoCDescription: new FormControl(''),
    MoCReportDateTime: new FormControl(''),
  });

  

  onFileSelected(event: any) {
    const file = (event.target as HTMLInputElement).files;
    this.form.patchValue({ Image: file });
    const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];

    {
      const reader = new FileReader();
      reader.onload = () => {
        this.imageData = reader.result as string;
      };
      if (file) {
        reader.readAsDataURL(file[0]);
      }
    }
    console.log(event.target.files[0]);
    const Image = event.target.files[0];
    this.image = Image;
  }

  addMOCForm() {
    console.log('adding');this.MoCReportDateTime, this.mocImage);
    const formData = new FormData();
    formData.append('facilityName', this.form.value.facilityName);
    formData.append('MoCDescription', this.form.value.MoCDescription);
    formData.append(
      'MoCReportDateTimeString',
      this.form.value.MoCReportDateTimeString
    );
    formData.append('mocImage', this.image);
    this.mocreportservice.postMOCForm(formData).subscribe((d) => {
      console.log(d);
    });
    this.router.navigate(['/message-board']);
  }
  
  ngOnInit(): void {}
}

I am creating a MEAN application that can perform CRUD operations, however when i am creating the update function the form fields are not populated with the already existing data to be updated.
HTML:

<button
              mat-button
              color="basic"
              [routerLink]="['/moc-report', mocreport._id]"
            >
              Update Status
            </button>

This is the button but to update but the form does not contain the data needed to update:
HTML of the form to contain the data to be updated:

<div class="container">
  <!--Navbar-->
  <mat-toolbar color="primary">
    <div class="centerNavBar">
      <a mat-button href="fa-dashboard">Back</a>
       
      <span class="headSpacer">Damage Assessment Tool</span>
       
      <a mat-button href="">Logout</a>
    </div>
  </mat-toolbar>
</div>

<div>
  <mat-sidenav-container class="MainContainter">
    <!--SideNav-->
    <mat-sidenav mode="side" opened>
      <div>
        <a mat-button href="">Message Board</a>
      </div>
    </mat-sidenav>
    <mat-sidenav-content class="MainContent">
      <mat-card>
        <mat-card-header class="sect">Create report:</mat-card-header>
        <br /><br />
        <mat-card-content class="centerAlign">
          <!--Div for form-->
          <div>
            <form [formGroup]="form" (submit)="addMOCForm()">
              <mat-form-field class="formwidth">
                <input
                  matInput
                  class="form-control"
                  formControlName="MoCReportDateTime"
                  type="Date"
                  required
                />
              </mat-form-field>
              <br />
              <mat-form-field>
                <mat-label>Comment</mat-label>
                <input
                  placeholder="--"
                  matInput
                  formControlName="MoCDescription"
                  class="form-control"
                  type="string"
                  required
                />
              </mat-form-field>
              <br />
              <mat-form-field>
                <mat-label>Facility In Question</mat-label>
                <input
                  placeholder="--"
                  matInput
                  formControlName="facilityName"
                  class="form-control"
                  type="string"
                  required
                />
              </mat-form-field>
              <mat-card class="centerAlign">
                <mat-card-actions>
                  <!--Div for buttons-->
                  <div>
                    <input
                      style="display: none"
                      #ImageInput
                      type="file"
                      (change)="onFileSelected($event)"
                    />

                    <button
                      mat-raised-button
                      type="button"
                      (click)="ImageInput.click()"
                    >
                      Upload Images
                    </button>
                     
                    <button mat-raised-button color="primary" type="submit">
                      Add
                    </button>
                  </div>
                </mat-card-actions>
              </mat-card>
            </form>
          </div>
        </mat-card-content>
      </mat-card>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

TS:

import { AfterViewInit, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {
  FormBuilder,
  FormGroup,
  FormControl,
} from '@angular/forms';

import { HttpClient } from '@angular/common/http';

import { MOCReportService } from 'src/app/service/mocreport.service';

@Component({
  selector: 'app-moc-report',
  templateUrl: './moc-report.component.html',
  styleUrls: ['./moc-report.component.css'],
})
export class MocReportComponent implements OnInit {
  
  image: any;
  Image = [];
  imageData: any;

  constructor(
    private mocreportservice: MOCReportService,
    //private mapService: MocMapService,
    private router: Router,
    private fb: FormBuilder,
    private http: HttpClient
  ) {}
  form = new FormGroup({
    facilityName: new FormControl(''),
    MoCDescription: new FormControl(''),
    MoCReportDateTime: new FormControl(''),
  });

  

  onFileSelected(event: any) {
    const file = (event.target as HTMLInputElement).files;
    this.form.patchValue({ Image: file });
    const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];

    {
      const reader = new FileReader();
      reader.onload = () => {
        this.imageData = reader.result as string;
      };
      if (file) {
        reader.readAsDataURL(file[0]);
      }
    }
    console.log(event.target.files[0]);
    const Image = event.target.files[0];
    this.image = Image;
  }

  addMOCForm() {
    console.log('adding');this.MoCReportDateTime, this.mocImage);
    const formData = new FormData();
    formData.append('facilityName', this.form.value.facilityName);
    formData.append('MoCDescription', this.form.value.MoCDescription);
    formData.append(
      'MoCReportDateTimeString',
      this.form.value.MoCReportDateTimeString
    );
    formData.append('mocImage', this.image);
    this.mocreportservice.postMOCForm(formData).subscribe((d) => {
      console.log(d);
    });
    this.router.navigate(['/message-board']);
  }
  
  ngOnInit(): void {}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黯然#的苍凉 2025-01-17 21:24:51

您的问题缺少两件事 - 1.缺少更新表单值的代码。 2.您想要在表单中更新哪些值以及它们在上面提供的代码片段中的位置。

我仍然为您提供解决方案
1.首先更新您的 html 并添加一个单击事件,该事件将用于在单击按钮

HTML:

<button
      mat-button
      color="basic"
      [routerLink]="['/moc-report', mocreport._id]"
      (click)="onUpdateClik()">
      Update Status
    </button>

TS:时更新表单

onUpdateClik(){
        //I'm assuming you want to update the form values which you are getting in form from the template.
        //If you are getting the form values from any API then append those values and you'll be done.
        this.form.patchValue({
            facilityName: this.form.value.facilityName, //update your respective values
            MoCDescription: this.form.value.MoCDescription, //update your respective values
            MoCReportDateTime: this.form.value.MoCReportDateTimeString, //update your respective values
        })
        }

your question is missing two things - 1.code to update the form values is missing. 2.what values you want to update in the form and where are they in the code snippet provided above.

Still I am providing you the solution
1.First update your html and add a click event which will be used for updating the form on click of button

HTML:

<button
      mat-button
      color="basic"
      [routerLink]="['/moc-report', mocreport._id]"
      (click)="onUpdateClik()">
      Update Status
    </button>

TS:

onUpdateClik(){
        //I'm assuming you want to update the form values which you are getting in form from the template.
        //If you are getting the form values from any API then append those values and you'll be done.
        this.form.patchValue({
            facilityName: this.form.value.facilityName, //update your respective values
            MoCDescription: this.form.value.MoCDescription, //update your respective values
            MoCReportDateTime: this.form.value.MoCReportDateTimeString, //update your respective values
        })
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文