Table 行编辑功能在 angular 中不起作用

Table row edit function is not working in angular

我想获取 table 的输入字段,然后删除或编辑行。我已经完成删除行但编辑功能不起作用

我尝试了下面的代码,在将数据提交到 table 之前它给出了正确的输出,即使删除行也有效 但是当我试图编辑编辑中给出的行输入时,模态正在考虑提交按钮和 它创建一个新行而不是更新 table 行

中的现有数据
 <div class="card">
      <form [formGroup]="userform">
        <div class="mt-5 box">
          <div class="form-row">
            <div class="col-md-12">
              <div class="formgroup mt-4">
                <label>Name</label>
              </div>
              <div class="form-row" style="margin-top: -10px;">
                <div class="col">
                  <input type="text" formControlName="name" class="form-contorl" placdeholder="name">
                </div>
    
              </div>
            </div>
            <div class="col-md-12">
              <div class="formgroup mt-4">
                <label>Phone number</label>
              </div>
              <div class="form-row" style="margin-top: -10px;">
                <div class="col">
                  <input type="text" formControlName="Phone" class="form-contorl" placdeholder="Phone number">
                </div>
    
              </div>
              <div class="form-row mt-4">
                <div class="col-md-2">
                  <button type="button" class="btn btn-primary" [disabled]="!userform.valid"
                    (click)="submit()">submit</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
      <div class="col-md mt-4 mb-4">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Phone</th>
              <th>Remove</th>
              <th>Edit</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let item of listdata">
              <td><span>{{item.name}}</span></td>
              <td><span>{{item.Phone}}</span></td>
    
              <td><button type="button" class="btn btn-danger" (click)="removeitem(item)">Remove</button></td>
              <td><button type="button" data-toggle="modal" data-target="#exampleModal" class="btn btn-primary"
                  (click)="edit(item)">Edit</button></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Update</h5>
            <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
    
            <form [formGroup]="userform">
    
              <div class="input-group form-group">
                <input type="text" class="form-control" formControlName="name" placeholder="Name">
              </div>
              <div class="input-group form-group">
                <input type="text" class="form-control" formControlName="Phone" placeholder="Phone number">
              </div>
              <div class="col-md-2">
                <button type="button" class="btn btn-primary" [disabled]="!userform.valid"
                  (click)="update()">update</button>
              </div>
            </form>`
          </div>
        </div>
      </div>
    </div>

ts code

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

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss'],
})
export class ContactComponent implements OnInit {
  userform: FormGroup;
  listdata: any;
  index: any;
  itemobj: any;
  constructor(private route: Router, private formbuilder: FormBuilder) {
    this.listdata = [];
    this.userform = this.formbuilder.group({
      name: ['', Validators.required],
      Phone: ['', Validators.required],
    });
  }

  submit(): void {
    this.listdata.push(this.userform.value);
    this.userform.reset();
  }

  update(): void {
    this.listdata[this.index] = this.itemobj;

    // this.listdata.push(this.userform.value);
    // this.userform.reset();
  }
  edit(item: any): void {
    this.userform.patchValue({
      // name:this.userform.get("name")?.value,
      // Phone:this.userform.get("Phone")?.value
      name: item.name,
      Phone: item.Phone,
    });
    this.itemobj = item;
    this.index = this.listdata.indexOf(item);
  }

  removeitem(element: any) {
    this.listdata.forEach((value: any, index: any) => {
      if (value == element) this.listdata.splice(index, 1);
    });
  }

  ngOnInit(): void {}
}

问题

  1. 您应该不要为您的创建和编辑表单使用相同的[formGroup]名称。当您单击 'Edit' 联系人记录时,您的两个表单(创建、编辑)都将与该值绑定。

  2. update 方法中,您正在存储 Contact 项值 (itemObj),该值是在 edit 方法中分配的值。 itemObj 值未根据表单值 更新。因此,您选择的联系人不会更新为新值。

update(): void {
    this.listdata[this.index] = this.itemobj;
}

解决方案

  1. 为您的编辑表单应用另一个 [formGroup] 名称并为其创建另一个 formbuilder

  2. 使用 <form>.value 从您的编辑表单中检索值并在下一次更新数组。

let user = this.editUserForm.value;

您的源代码应为:

contact.component.html (for edit form only)

<!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Update</h5>
            <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
    
            <form [formGroup]="editUserForm">
    
              <div class="input-group form-group">
                <input type="text" class="form-control" formControlName="name" placeholder="Name">
              </div>
              <div class="input-group form-group">
                <input type="text" class="form-control" formControlName="Phone" placeholder="Phone number">
              </div>
              <div class="col-md-2">
                <button type="button" class="btn btn-primary" [disabled]="!editUserForm.valid"
                  (click)="update()">update</button>
              </div>
            </form>`
          </div>
        </div>
      </div>
    </div>

contact.component.ts

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

@Component({
  selector: 'app-contact',
  templateUrl: `./contact.component.html`,
  styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit  {
userform: FormGroup;
editUserForm; FormGroup;
  listdata: any;
  index: any;
  itemobj: any;

  constructor(private route: Router, private formbuilder: FormBuilder) {
    this.listdata = [];
    this.userform = this.formbuilder.group({
      name: ['', Validators.required],
      Phone: ['', Validators.required],
    });

    this.editUserForm = this.formbuilder.group({
      name: ['', Validators.required],
      Phone: ['', Validators.required],
    });
  }

  submit(): void {
    this.listdata.push(this.userform.value);
    this.userform.reset();
  }

  update(): void {
    let user = this.editUserForm.value;

    this.listdata[this.index] = user;
    this.editUserForm.reset();
  }
  
  edit(item: any): void {
    this.editUserForm.patchValue({
      // name:this.userform.get("name")?.value,
      // Phone:this.userform.get("Phone")?.value
      name: item.name,
      Phone: item.Phone,
    });
    this.itemobj = item;
    this.index = this.listdata.indexOf(item);
  }

  removeitem(element: any) {
    this.listdata.forEach((value: any, index: any) => {
      if (value == element) this.listdata.splice(index, 1);
    });
  }

  ngOnInit(): void {}
}

Sample StackBlitz