angular - 如何有条件地向表中添加一行?
问题描述
我正在构建一个角度应用程序,我将在其中将项目添加到表格中。添加的行将基于项目名称及其数量的输入。
如果出现以下情况,我正在努力防止将项目添加到表格中:
- 未选择任何内容或
- 在数量字段中输入非正数(数量字段仅接受自然数)
如果不满足这些条件中的任何一个,将显示一条错误消息。我能够显示错误消息,但添加了一行无效字段。
注意:如果不满足条件,我不允许禁用“添加项目”按钮。
这是我的代码:
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
}
}
解决方案
只需在 add 方法的开头添加一个条件:
addItem() {
if(!this.newItem || !this.newItem.name ||
(this.newItem && !this.newItem.name)) {
return;
}
this.items.push(this.newItem);
this.newItem = {};
}
推荐阅读
- r - R - 创建一列字符矩阵
- batch-file - 批处理文件:从文本文件中合并同名文本文件
- sql - JOIN ON SQL 语法
- java - ChromeDriver 和 WebDriver for Selenium 通过 TestNG 导致 4 个错误
- r - 有条件地用R中数据框中的字符串替换NA
- java - 在一个线程中创建数据库实体并尝试在另一个线程中检索相同的实体会给出不同的结果
- qt - 如何将定义列表加载到 QML 中?
- python - 读取 SAS 文件以获取元信息
- c# - 在 IIS 中未找到返回 404 的 MVC 控制器操作上调用 Get
- android - 注释处理器现在必须显式声明。- 黄油刀7.0.1.jar(黄油刀7.0.1.jar)