【问题标题】:Populating Angular's Reactive form with data from server使用来自服务器的数据填充 Angular 的响应式表单
【发布时间】:2020-09-12 04:18:03
【问题描述】:

尝试将服务器数据插入 Angular 的表单,以便 FormGroup 属性键是来自服务器数据的键。遵循 Angular 的动态表单文档,但这并不是我想要的 (https://angular.io/guide/reactive-forms#creating-dynamic-forms)。

重点是用数据填充表单并在模板中显示它,*ngFor 使用每个属性上的滑块来获取一个值。然后将数据发送回服务器。

数据对象示例:

{
  "things": [
    {
      "thingId": 1,
      "thingName": "bear"
    },
    {
      "thingId": 2,
      "thingName": "piano"
    }
  ]
}

服务获取数据并分配给变量:

things: IThing[] = [];

getThings() {
  this.thingService.getThings()
    .subscribe(data => {
      this.things = data.things;
    });
}

我需要用从服务器获取的数据对象的值填充thingsFormGroup(或FormArray,如果需要),即thingName属性值=>“bear”,“piano”。

ngOnInit() {
  this.myForm = this.fb.group({
    title: ['', []],
    comment: ['', []],

    // need to populate the things object here, example:
    things: this.fb.group([
      // bear: [,[]],
      // piano: [,[]]
      // and so on...
    ])
  })

  this.getThings();
}

【问题讨论】:

    标签: javascript arrays angular forms angular-reactive-forms


    【解决方案1】:

    您可以创建一个 empy FormGroup 并使用addControl 来添加一个具有属性名称的控件

    things: this.fb.group({}) //<--a empty formGroup
    

    并在订阅的东西

    this.thingService.getThings()
        .subscribe(data => {
          this.things = data.things;
          this.things.forEach(x=>{
              (this.myForm.get('things') as FormGroup)
                     .addControl(x.thingName,this.fb.control(''))
          })
        });
    

    注意:在 .html 中你有一些类似

    <form [formGroup]="myForm">
      ...
      <div formGroupName="things">
          <div *ngFor="let thing of things">
              <input [formControlName]="thing.thingName">
          </div>
      </div>
    </form>
    

    更新另一件事是你真的想要一个FormArray,你需要考虑你的数据库(如果你想存储在数据库中)。在这种情况下,您只需要一个 FormControls 的 FormArray,因此,首先您创建一个空的 FormArray

    things: this.fb.array([]) //<--a empty formArray
    

    而且,在 subscribe 中,您向 formArray 添加了许多控件,因为元素具有这些东西

    this.thingService.getThings()
        .subscribe(data => {
          this.things = data.things;
          this.things.forEach(x=>{
              (this.myForm.get('things') as FormArray)
                     .push(this.fb.control(''))
          })
        });
    

    和.html之类的

    <form [formGroup]="myForm">
      ...
      <div formArrayName="things">
          <div *ngFor="let controls of thingsArray.controls;let i=index">
              {{things[i].thingName}}:<input [formControlName]="i">
          </div>
      </div>
    </form>
    

    使用getter获取数组

    get thingsArray()
      {
        return this.myForm.get('things') as FormArray
      }
    

    我把这两种情况都放在了stackblitz - 在堆栈闪电战中你有 myForm 和 myForm2-

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      相关资源
      最近更新 更多