Angular 2 with an array of object input

I am creating a billing application to learn Angular2. The problem I am facing is how to create a position component where the line contains 3 inputs that must come in and snap to the object in the position array.

In angular 1, I can easily achieve this by adding a directive ng-formto the inputs container. What is equivalent here?

Here is my code:

HTML:

<form name="form" ng-submit="$ctrl.submit(form)" novalidate>

<!-- some more code -->

<ul class="list invoice-table__body">
  <li *ngFor="let item of model.lineItems; let i = index">
    <input
      type="text"
      name="description"
      class="col-sm-8"
      [(ngModel)]="item.description">

    <input
      type="number"
      name="quantity"
      class="col-sm-2"
      [(ngModel)]="item.quantity">

    <input
      type="number"
      name="total"
      class="col-sm-2"
      [(ngModel)]="item.total">
  </li>
</ul>

<!-- some more code -->

</form>

component:

import { Component } from '@angular/core';
import { Invoice } from './invoice.model';
import { InvoiceLineItems } from './invoice-line-item.model';

@Component({
  selector: 'create-invoice',
  templateUrl: 'create-invoice/create-invoice.html'
})
export class CreateInvoiceComponent {
  model: Invoice = new Invoice(
    85,
    'CAD',
    null,
    [ // lineItems
      new InvoiceLineItems('Web development for BAnQ'),
      new InvoiceLineItems('Sept 1 to 3', 14, 910),
      new InvoiceLineItems('Sept 5 to 10', 34, 5293),
      new InvoiceLineItems('Sept 11 to 20', 24, 5293),
      new InvoiceLineItems('Sept 21 to 38', 11, 2493),
    ],
    13989,
    100,
    200,
    15000,
    '',
    null,
    '$'
  );

  getTotal(): number {
    return this.model.lineItems.reduce(
      (a, b): number => a + (isNaN(b.total) ? 0 : b.total),
      0);
  }
}
+1
source share
1 answer

, name = "description", , , , form.description.value . , form.description [i].value

, .

name= " _ {{}}"

ngFor. :

<ul class="list invoice-table__body">
  <li *ngFor="let item of invoice.lineItems; let i = index">

    <input
      type="text"
      name="description_{{i}}"
      class="col-sm-8"
      [(ngModel)]="invoice.lineItems[i].description">

    <input
      type="number"
      name="quantity_{{i}}"
      class="col-sm-2"
      [(ngModel)]="invoice.lineItems[i].quantity">

    <input
      type="number"
      name="total_{{i}}"
      class="col-sm-2"
      [(ngModel)]="invoice.lineItems[i].total">
  </li>
</ul>

, : https://plnkr.co/edit/orldGCSYDUtlxzMFsVjL?p=preview

ReactiveForms (Model Driven Forms), , , FormsModule (Template Driven Forms), . .

, .

+10

All Articles