Y_Lakdime
Y_Lakdime

Reputation: 825

How do I set the input value in Angular 8?

I am building an invoice feature inspired from this site and I want the first two lines of the invoice to be pre-filled with: 'Hours worked' & 'Kilometers travelled'. The example code of the mentioned site is using the first version of Angularjs so I need to transform that into Angular 2+, so i changed ng-model="items.description" into [(ngModel)]="items.description"

In my invoice.component.ts I have declared this field:

  items:[
{ qty: 1, description: 'Hours worked', cost: 500 },
{ qty: 1, description: 'Kilometres traveled', cost: 4500 }

]; This is the full code block :

<div class="row invoice-item" *ngFor="let item of items" ng-animate="'slide-down'">
    <div class="col-xs-1 remove-item-container">
      <a href ng-hide="printMode" ng-click="removeItem(item)" class="btn btn-danger">[X]</a>
    </div>
    <div class="col-xs-5 input-container">
      <input [(ngModel)]="items.description" placeholder="description" >
    </div>
    <div class="col-xs-2 input-container">
      <input ng-model="item.qty" value="1" size="4" ng-required ng-validate="integer" placeholder="Quantity" />
    </div>
    <div class="col-xs-2 input-container">
      <input ng-model="item.cost" value="0.00" ng-required ng-validate="number" size="6" placeholder="Cost" />
    </div>
    <div class="col-xs-2 text-right input-container">
      <!-- {{item.cost * item.qty | currency: currencySymbol}} -->
    </div>
  </div>

However, the lines are blank. What am I doing wrong?

(i know the rest of the code is still using Angularjs code, but that is not relevant right now)

Upvotes: 0

Views: 2271

Answers (1)

Venusssss
Venusssss

Reputation: 528

as @Ingo Burk mentioned above you just need to adjust the "items" from your code to "item"

Your code

      <input [(ngModel)]="items.description" placeholder="description" >
...

to this

      <input [(ngModel)]="item.description" placeholder="description" >
...

Explain: when you use *ngFor="let item of items", the "let item of items" means let the "item" contains all the data of "items" so from that you just simply use the "item". [(ngModel)] works as 2-way data binding which means the user can type in and see the output at the same time. I hope this will help you. Corrections are all welcome

Upvotes: 1

Related Questions