Angular 5 FormArray 从数据库中获取数据并显示行

Angular 5 FormArray get data from database and show rows

我只是 angular 的新手。我已经创建了一个事件组件,用户可以在其中输入带有包的事件名称。当用户创建事件时,它具有使用添加和删除行创建多个包的功能。为此,我使用了 FormArray.

这里一切都很好。但是当我试图在事件编辑组件中获取这些值时,我得到的是事件名称的值,但是当我试图获取包的详细信息时,我在显示带有填充值的行时有点困惑。

这是我到目前为止所做的代码

事件-edit.component .ts 看起来像这样

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { FormControlName } from '@angular/forms/src/directives/reactive_directives/form_control_name';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { EventService } from '../event.service';


@Component({
  selector: 'app-event-edit',
  templateUrl: './event-edit.component.html',
  styleUrls: ['./event-edit.component.css']
})
export class EventEditComponent implements OnInit {

  event = {};


  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute,
    private formBuilder : FormBuilder,
    private eventService : EventService,
    ) { this.createEventForm(); }

  createEventForm() {
    this.form = this.formBuilder.group({
      eventname: ['', Validators.compose([
        Validators.required,
        Validators.minLength(5)
      ])],
    })
  }

  ngOnInit() {
    this.getOneEvent(this.route.snapshot.params['id']);
    this.form = new FormGroup({
      eventname: new FormControl('', [ Validators.required, Validators.minLength(5)]),
      sections: new FormArray([
        this.initSection(),
      ]),
    });
  }

  getOneEvent(id) {
    this.http.get( this.domain + '/api/event/' + id).subscribe(data => {
      this.event = data['eventname'];
      this.packages = data['packages']; //getting packages as array object
    });

  }

  public addPackageRow() {
    const control = <FormArray>this.form.get('sections');
    control.push(this.initSection());
  }

  addSection() {
    const control = <FormArray>this.form.get('sections');
    control.push(this.initSection());
  }

  initSection() {
    return new FormGroup({
      packagename: new FormControl('', [ Validators.required, Validators.minLength(5)]),
      packageprice: new FormControl(''),
      packagelimit: new FormControl('')
    });
  }

  getSections(form) {
    return form.controls.sections.controls;
  }

  public removeSection(i){
    const control = <FormArray>this.form.get('sections');
     control.removeAt(i);
  }

}

事件-edit.component.html看起来像这样

<div class="container col-md-10">
  <h1 class="page-header">Event Edit</h1>
  <!-- <div class="row show-hide-message">
    <div [ngClass]= "messageClass">{{message}}</div>
  </div> -->
  <form [formGroup] = "form" (ngSubmit)="updateEvent(event._id)">
    <fieldset>
      <div class="form-group">
        <label for="eventname">Event Name</label>
        <div class='form-group'>
          <input type="text" formControlName="eventname" class="form-control" autocomplete="off" [(ngModel)]="eventname" placeholder="Event Name" >
        </div>
      </div>


      <h4>Package Price</h4>
      <hr>
      <div class="row" formArrayName="sections">
        <div class="col-md-12" *ngFor="let section of getSections(form); let i = index" [formGroupName]="i">

        <div class="form-group col-md-5">
          <label for="packagename">Package Name</label>
          <input type="text" class="form-control" autocomplete="off" placeholder="Package Name" formControlName="packagename">
       </div>
        <div class="form-group col-md-2">
          <label for="packageprice">Package Price</label>
          <input type="number" class="form-control" autocomplete="off" placeholder="Package Price" formControlName="packageprice" >
        </div>
        <div class="form-group col-md-3">
          <label for="packagelimit">Max Purchase Limit</label>
          <input type="number" class="form-control" formControlName="packagelimit" autocomplete="off" >
        </div>
        <div class="form-group col-md-1">
          <br/>
          <input type="button" (click)="addPackageRow()" class="btn btn-md btn-success" value="+" name="">
        </div>
        <div class="form-group col-md-1" *ngIf="getSections(form).length > 1">
          <br/>
          <input type="button" (click)="removeSection(i)" class="btn btn-md btn-error" value="-" name="">
        </div>
      </div>
      </div>
      <input type="submit" class="btn btn-primary" value="Update">
    </fieldset>
  </form>
</div>

您只需循环遍历包中的数据并将其添加到表单中。

服务完成后,您将初始化循环 :-

 getOneEvent(id) {
    this.http.get( this.domain + '/api/event/' + id).subscribe(data => {
      this.event = data['eventname'];
      this.packages = data['packages']; //getting packages as array object
      for(let package of this.packages){
        this.addSection(package)
      }
    });

  }

然后在您的 sections 函数中将其传递给 initSection。

addSection(package) {
    const control = <FormArray>this.form.get('sections');
    control.push(this.initSection(package));
  }

然后最后在你的 initSection 中你将赋值

initSection(package) {
      if (!package) {
        var package = {
          packagename : "",
          packageprice : "",
          packagelimit : ""
        }
      }
      return new FormGroup({
        packagename: new FormControl(package.packagename, [Validators.required, Validators.minLength(5)]),
        packageprice: new FormControl(package.packageprice),
        packagelimit: new FormControl(package.packagelimit)
      });
    }

if 条件用于添加空白(新)项目。

同时从 ngOnInit 中删除对 addSection 的调用,否则第一行将留空。