【问题标题】:Angular 4 : How to dynamically add and delete rows in a tableAngular 4:如何动态添加和删除表中的行
【发布时间】:2017-10-04 10:12:47
【问题描述】:

在我的 Angular 应用程序中,我有 3 个输入,比如代码、名称和价格。并且有一个表格显示用户选择。

当我点击添加按钮时,下拉列表中的选择应该被填充到表格中,

Product     Price      Action
124578-ABC  100        <Delete Button>

当我点击删除按钮时,相应的行应该被删除。 我尝试使用 jquery 执行此操作。但我想知道这样做的角度。

【问题讨论】:

  • 创建一个数组,单击添加后将推送新对象并使用 *ngFor 在 html 中显示此数组
  • 如果你使用 angular,你拥有的 jquery 越少越好。也欢迎一些 html 代码
  • 利用 porgo 给出的想法,否则转移到reactive forms
  • 你解决了吗?
  • 要显示数据,将其推送到控制器端的可观察对象。绑定该 observable 以显示您的数据。要删除,请从用于显示下表的 observable 中删除并重新绑定。波尔戈是正确的。由于数据不是来自数据库,请使用数组。这也行。

标签: angular


【解决方案1】:

试试这样:

在这个例子中我只是使用了文本框而不是你的输入类型

表格样

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Code</th>
            <th>Name</th>
            <th>Price</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let field of fieldArray; let i = index">
            <td>
                <input [(ngModel)]="field.code" class="form-control" type="text" name="{{field.code}}" />
            </td>
            <td>
                <input [(ngModel)]="field.name" class="form-control" type="text" name="{{field.name}}" />
            </td>
            <td>
                <input [(ngModel)]="field.price" class="form-control" type="text" name="{{field.price}}" />
            </td>
            <td>
                <button class="btn btn-default"  type="button" (click)="deleteFieldValue(i)">Delete</button>
            </td>
        </tr>
        <tr>
            <td>
                <input class="form-control" type="text" id="newAttributeCode" [(ngModel)]="newAttribute.code" name="newAttributeCode" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributeName" [(ngModel)]="newAttribute.name" name="newAttributeName" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributePrice" [(ngModel)]="newAttribute.price" name="newAttributePrice" />
            </td>
            <td>
                <button class="btn btn-default" type="button" (click)="addFieldValue()">Add</button>
            </td>
        </tr>
    </tbody>
</table>

打字稿示例:

export class Component {
    private fieldArray: Array<any> = [];
    private newAttribute: any = {};

    addFieldValue() {
        this.fieldArray.push(this.newAttribute)
        this.newAttribute = {};
    }

    deleteFieldValue(index) {
        this.fieldArray.splice(index, 1);
    }
}

【讨论】:

  • @Candru 谢谢,它就像一个魅力。但是如果 fieldArray 最初为 null 以使行中存在一个空文本框,该怎么办
  • @AbhishekEkaanth 我知道为时已晚。但可能对其他人有帮助。您可以在 ngOnInit() 方法中添加 addFieldValue() 方法中的两行代码。像这样 ngOnInit(): void { this.fieldArray.push(this.newAttribute) this.newAttribute = {}; }
  • @Chandru 当我单击添加按钮并在行中输入/选择值然后再次单击添加按钮以输入值时,它会删除我在第一行中输入/选择的所有值.你知道如何解决这个问题吗?
  • @Chandru 我试图在我的项目中实现你的想法。我有一个问题。想知道你是否可以帮助我。 ~苏迪尔stackoverflow.com/questions/50723261/…
  • @Chandru,如果我想在表格的最开头添加一个字段怎么办?
【解决方案2】:

试试这个:

grid-view-component.html

<div class="container" style="margin-top: 5%">    
        <table class="table table-striped table-bordered">    
            <thead>    
                <tr>    
                    <th>Action</th>    
                    <th>Nmae</th>    
                    <th>Email</th>    
                    <th>Phone</th>    
                </tr>    
            </thead>    
            <tbody>    
                 <tr *ngFor="let dynamic of dynamicArray; let i = index;">    
                  <td (click)="deleteRow(i)">    
                    <i class="fa fa-trash fa-2x"></i>    
                  </td>    
                    <td>    
                      <input [(ngModel)]="dynamicArray[i].name" class="form-control" type="text" />    
                    </td>    
                    <td>    
                      <input [(ngModel)]="dynamicArray[i].email" class="form-control" type="email" />    
                    </td>    
                    <td>    
                      <input [(ngModel)]="dynamicArray[i].phone" class="form-control" type="number"/>    
                    </td>    
                </tr>    
                <tr>    
                  <td (click)="addRow()">    
                    <i class="fa fa-plus fa-2x"></i>    
                  </td>    
                </tr>    
            </tbody>    
        </table>    
</div>  

grid-view-component.ts

import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';  
import { DynamicGrid } from '../grid.model';

@Component({
  selector: 'app-grid-view',
  templateUrl: './grid-view.component.html',
  styleUrls: ['./grid-view.component.css']
})
export class GridViewComponent implements OnInit {

      constructor(private toastr: ToastrService) { }  

      dynamicArray: Array<DynamicGrid> = [];  
      newDynamic: any = {}; 

      ngOnInit(): void {  
          this.newDynamic = {name: "", email: "",phone:""};  
          this.dynamicArray.push(this.newDynamic);  
      }  

      addRow() {    
        this.newDynamic = {name: "", email: "",phone:""};  
          this.dynamicArray.push(this.newDynamic);  
          this.toastr.success('New row added successfully', 'New Row');  
          console.log(this.dynamicArray);  
          return true;  
      }  

      deleteRow(index) {  
          if(this.dynamicArray.length ==1) {  
            this.toastr.error("Can't delete the row when there is only one row", 'Warning');  
              return false;  
          } else {  
              this.dynamicArray.splice(index, 1);  
              this.toastr.warning('Row deleted successfully', 'Delete row');  
              return true;  
          }  
      }
} 

grid.model.ts

export class DynamicGrid{     
    name:string;  
    email:string;  
    phone:string;  
}

【讨论】:

    【解决方案3】:

    只需添加具有相同字段的两行。一个具有相同字段的将避免 fieldArray 最初为 null,而另一个具有相同字段的 *ngFor 像这样

    <table>
    
    <tr>
    </tr>
    
    <tr *ngFor>
    </tr>
    
    </table>
    

    【讨论】:

    • 欢迎来到 Stack Overflow。请考虑其他现有且已接受的答案,并说明您的答案如何添加新信息。
    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2016-10-26
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2017-12-09
    相关资源
    最近更新 更多