我想用关闭(X)按钮动态添加文本框(最多10个),然后想要添加一些文本。单击“保存”按钮后,文本应显示在不同视图中。如果单击关闭按钮(X),则可以删除添加的文本框或文本。
视图可以使用编辑\关闭按钮切换。
答案 0 :(得分:4)
<强> app.component.ts 强>
fieldArray: Array<any> = [];
newAttribute: any = {};
firstField = true;
firstFieldName = 'First Item name';
isEditItems: boolean;
addFieldValue(index) {
if (this.fieldArray.length <= 2) {
this.fieldArray.push(this.newAttribute);
this.newAttribute = {};
} else {
}
}
deleteFieldValue(index) {
this.fieldArray.splice(index, 1);
}
onEditCloseItems() {
this.isEditItems = !this.isEditItems;
}
<强> app.component.html 强>
<div class="container">
<br>
<div class="row">
<table class="table table-striped table-bordered col-lg-4">
<caption><i>Add/remove textbox and chip dynamically in Angular 6</i></caption>
<thead>
<tr>
<th>Item Name
<a (click)="onEditCloseItems()" class="text-info float-right">
<i class="mdi mdi-{{isEditItems ? 'close' : 'pencil'}} mdi-18px"></i>
</a>
</th>
</tr>
</thead>
<tbody *ngIf="!isEditItems">
<tr *ngIf="firstField">
<td>
<i (click)="firstField = false" class="mdi mdi-close mdi-18px"></i> {{firstFieldName}}
</td>
</tr>
<tr *ngFor="let field of fieldArray; let i = index">
<td *ngIf="field?.name">
<i (click)="deleteFieldValue(i)" class="mdi mdi-close mdi-18px"></i> {{field.name}}</td>
</tr>
</tbody>
<tbody *ngIf="isEditItems">
<tr>
<td *ngIf="firstField">
<div class="input-group">
<div class="input-group-prepend">
<div (click)="firstField = false" class="input-group-text"><i class="mdi mdi-close mdi-18px"></i></div>
</div>
<input [(ngModel)]="firstFieldName" class="form-control py-2 " type="text" name="firstFieldName" placeholder="Item Name">
</div>
</td>
</tr>
<tr *ngFor="let field of fieldArray; let i = index">
<td>
<div class="input-group">
<div class="input-group-prepend">
<div (click)="deleteFieldValue(i)" class="input-group-text"><i class="mdi mdi-close mdi-18px"></i></div>
</div>
<input [(ngModel)]="field.name" class="form-control" type="text" name="{{field.name}}" placeholder="Item Name">
</div>
</td>
</tr>
<tr>
<td align="right">
<button *ngIf="fieldArray.length <= 2" class="btn btn-success btn-sm" type="button" (click)="addFieldValue()" style="margin-right:10px">Add More Item</button>
<button (click)="onEditCloseItems()" class="btn btn-primary btn-sm" type="button">Save Items</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<强>被修改强> Stackblitz demo link 2