首页 > 解决方案 > 如何有条件地向表中添加一行?

问题描述

我正在构建一个角度应用程序,我将在其中将项目添加到表格中。添加的行将基于项目名称及其数量的输入。

如果出现以下情况,我正在努力防止将项目添加到表格中:

如果不满足这些条件中的任何一个,将显示一条错误消息。我能够显示错误消息,但添加了一行无效字段。

注意:如果不满足条件,我不允许禁用“添加项目”按钮。

这是我的代码:

app.component.html

<form #order="ngForm">
    <table>
      <tr>
        <td>
          <button type="submit" class="btn btn-default" (click)="addItem()">Add
            Item</button>
        </td>
        <td>
          <select [(ngModel)]="newItem.name" required name="newItemName" #newItemName="ngModel" minlength="1">
            <option *ngFor="let o of options" [ngValue]="o">{{o.name}}</option>
          </select>
        </td>
        <td>Qty</td>
        <td>
          <input type="text" pattern="[0-9]*" required [(ngModel)]="newItem.quantity" 
          name="newItemQuantity" #newItemQuantity="ngModel">
        </td>
      </tr>
    </table>
    <p *ngIf="newItemName?.errors?.required && order.submitted">Please select an item.</p>
    <p *ngIf="newItemQuantity?.errors?.required && order.submitted">Quantity is required.</p>
  </form>
  <table>
    <thead>
      <tr>
        <th>Item</th>
        <th>Qty</th>
        <th>Unit Price</th>
        <th>Amount</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of items; let i = index">
        <td><label class="form-control">{{item.name.name}}</label></td>
        <td><label class="form-control">{{item.quantity}}</label></td>
        <td><label class="form-control">{{item.name.price}}</label></td>
        <td></td>
        <td><input type="button" value="delete" (click)="removeItem(i)"></td>
      </tr>
    </tbody>
  </table>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})

export class AppComponent {
  items: Array<any> = [];
  newItem: any = {};
  options = [
    {name: "apples", price: 1.19},
    {name: "peaches", price: 1.39},
    {name: "pears", price: 1.69},
    {name: "plums", price: 1.59}
  ];

  addItem() {
    if (this.newItem != undefined) {
      this.items.push(this.newItem);
      this.newItem = {};
    }
  }

  removeItem(index) {
    this.items.splice(index, 1); // remove 1 item at ith place
  }

}

项目仍在添加

标签: angular

解决方案


只需在 add 方法的开头添加一个条件:

addItem() {
  if(!this.newItem || !this.newItem.name || 
      (this.newItem && !this.newItem.name)) {
    return;
  }

  this.items.push(this.newItem);
  this.newItem = {};
}

推荐阅读