Setting values of input fields with Angular 6

后端 未结 2 449
小鲜肉
小鲜肉 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:07

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

    Template

    Global Price:
    {{orderLine.time | date}} {{orderLine.quantity}}

    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() {
    
      }
    }
    

提交回复
热议问题