Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting values of input fields with Angular 6

I've ran into some trouble setting the value of an input element using Angular.

I'm trying to set the value of dynamically created input elements in my application by this method:

copyPricingToAll(): void {
  var copyValue: string = document.getElementById("priceInputGlobal").value;

  this.currentItem.orderLines.forEach(orderLine => {
  document.getElementById("priceInput-" + orderLine.id).setAttribute("value", copyValue);
   });
  }

I'm creating the rows like this:

<ng-container *ngFor="let orderLine of currentItem.orderLines let i=index">
    <tr>
       <td>{{getCorrectTimeString(orderLine)}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input id="priceInput-{{orderLine.id}}" type="number" value="{{orderLine.price}}"></td>
    </tr>
</ng-container>

Unfortunately .value is not recognized as a valid operation. I'm not sure how to correctly set the value of a dynamically created element in angular. I hope someone is able to help me out with this issue.

like image 436
Mikey123 Avatar asked Jun 29 '18 07:06

Mikey123


People also ask

How do you set values in reactive form?

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances. patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls.

What is FormControlName in angular?

FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.


1 Answers

You should use the following:

<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

like image 175
William Moore Avatar answered Oct 16 '22 09:10

William Moore