代码之家  ›  专栏  ›  技术社区  ›  Binabiko

角度表输入值

  •  2
  • Binabiko  · 技术社区  · 7 年前

    观察输入HTML元素的值的最佳实践是什么?我需要动态添加尽可能多的输入。因此,我无法使用 ngModel .此时我正在使用 ElementRef

    <div class="item">
        <input type="text" id="firstName1">
        <input type="text" id="lastName1">
    </div>
    

    我试图创建一个对象,其中的值适应变化:

    let user = {
       firstName: ADAPT_TO_FIRSTNAME_VALUE,
       lastName: ADAPT_TO_LASTNAME_VALUE
    }
    

    解决方案方法:

    <form [formGroup]="user">
        <input type="text" formControlName="firstName">
        <input type="text" formControlName="lastName">
    </form>
    
    
    arr = new FormArray();
    user;
    
    create() {
        this.user = new FormGroup({
             firstName: new FormControl(),
             lastName: new FormControl()
        });
        this.arr.push(user);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Tomasz Kula    7 年前

    像这样的事情应该让你开始。

    import { Component,  } from '@angular/core';
    import { FormGroup, FormControl, FormBuilder } from '@angular/forms'
    
    @Component({
      selector: 'my-app',
      template: `
      <form [formGroup]="form">
        <input *ngFor="let control of controls" [formControl]="control" />
      </form>
    
      {{ user | json }}
      `,
      styles: [`input { width: 100%; }`]
    })
    export class AppComponent {
      form: FormGroup;
      controls: FormControl[];
    
      get user() {
        return this.form.value;
      }
    
      constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
          firstName: '',
          lastName: '',
          // add as much properties as you like
        })
    
        this.controls = Object.keys(this.form.controls).map(key => this.form.controls[key] as FormControl);
      }
    }
    

    我们创建一个 FormControl 对于每个用户对象属性。在 <input> html元素将反映在 FormGroup 的值。

    请注意,我正在使用 ReactiveFormsModule 您必须将其导入 AppModule

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { ReactiveFormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    
    @NgModule({
      imports: [BrowserModule, ReactiveFormsModule],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Live demo