动态添加HTML表单输入字段 - Angular 2

时间:2017-03-31 08:54:33

标签: html forms angular input dynamic

我尝试在ng2应用中添加动态行。贝娄样品工作正常。但是,如果我在HTML表单标记内移动此HTML模板表,它将不会显示文本框值。但文本框值保存在ngmodel中。如何显示文本框值?

HTML模板:

             <table>
                <tr>
                    <td>Item</td>
                    <td>Qty</td>
                    <td>UP</td>
                    <td>Total</td>
                </tr>
                <tr *ngFor="let row of invoiceItemsData; let i = index">
                    <td><input type="text" class="form-control" required [(ngModel)]="row.item_id" value="{{row.item_id}}" name="item_id"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.qty" value="{{row.qty}}" name="qty"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.unit_price" value="{{row.unit_price}}" name="unit_price"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.total" value="{{row.total}}" name="total"></td>
                    <a class="btn btn-primary" (click)="addNewRow()">New</a>
                </tr>
                {{invoiceItemsData|json}}
            </table>

NG2代码示例:

export class InvoiceFormComponent implements OnInit {

       public myForm: FormGroup;
       public invoiceItemsData = [{'item_id':'','qty':'','unit_price':'','total':''}] ;

       constructor(private formBuilder: FormBuilder) {}

       ngOnInit() {}

        addNewRow(){
          this.invoiceItemsData.push({'item_id':'','qty':'','unit_price':'','total':''})
        }
}

输出: enter image description here

将HTML表格添加到HTML中

<form  name="inv" novalidate (ngSubmit)="save(myForm)">
            <table class="table">
                <tr>
                    <td>Item</td>
                    <td>Qty</td>
                    <td>UP</td>
                    <td>Total</td>
                </tr>
                <tr *ngFor="let row of invoiceItemsData; let i = index">
                    <td><input type="text" class="form-control" required [(ngModel)]="row.item_id" value="{{row.item_id}}" name="item_id"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.qty" value="{{row.qty}}" name="qty"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.unit_price" value="{{row.unit_price}}" name="unit_price"></td>
                    <td><input type="text" class="form-control" required [(ngModel)]="row.total" value="{{row.total}}" name="total"></td>

                    <a class="btn btn-primary" (click)="addNewRow()">New</a>
                </tr>
                {{invoiceItemsData|json}}
            </table>
</form>

HTML表格移动到HTML表单时的输出: enter image description here

0 个答案:

没有答案