Setting values of input fields with Angular 6

后端 未结 2 447
小鲜肉
小鲜肉 2020-12-29 12:47

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

相关标签:
2条回答
  • 2020-12-29 13:00

    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)

    0 讨论(0)
  • 2020-12-29 13:07

    As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

    Template

    <form [formGroup]="mainForm" ng-submit="submitForm()">
      Global Price: <input type="number" formControlName="globalPrice">
      <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
      <table border formArrayName="orderLines">
      <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
        <tr>
           <td>{{orderLine.time | date}}</td>
           <td>{{orderLine.quantity}}</td>
           <td><input formControlName="price" type="number"></td>
        </tr>
    </ng-container>
      </table>
    </form>
    

    Component

    import { Component } from '@angular/core';
    import { FormGroup, FormControl, FormArray } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular 6';
      mainForm: FormGroup;
      orderLines = [
        {price: 10, time: new Date(), quantity: 2},
        {price: 20, time: new Date(), quantity: 3},
        {price: 30, time: new Date(), quantity: 3},
        {price: 40, time: new Date(), quantity: 5}
        ]
      constructor() {
        this.mainForm = this.getForm();
      }
    
      getForm(): FormGroup {
        return new FormGroup({
          globalPrice: new FormControl(),
          orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
        })
      }
    
      getFormGroupForLine(orderLine: any): FormGroup {
        return new FormGroup({
          price: new FormControl(orderLine.price)
        })
      }
    
      applyPriceToAll() {
        const formLines = this.mainForm.get('orderLines') as FormArray;
        const globalPrice = this.mainForm.get('globalPrice').value;
        formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
        // optionally recheck value and validity without emit event.
      }
    
      submitForm() {
    
      }
    }
    
    0 讨论(0)
提交回复
热议问题