如何预先填充Angular 2中的数据?使用FormGroup?

我正在Angular 2中构建一个表单.构建提交表单的过程很简单,但我还需要一个编辑功能.我的问题是我不明白如何从后端预先填充表单中的数据.我有一个后端服务,我从中获取数据.但我不知道这些数据将如何绑定到现有表单.

表格的代码如下: –

组件代码

import { Component, OnInit } from '@angular/core';

import { DialogRef, ModalComponent, CloseGuard } from 'angular2-modal';
import { BSModalContext } from 'angular2-modal/plugins/bootstrap';
import { ValidationService } from '../../../shared/core/error-messages/validation-service';

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

export class CustomModalContext extends BSModalContext {
  public num1: number;
  public num2: number;
}

/**
 * A Sample of how simple it is to create a new window, with its own injects.
 */
@Component({
  selector: 'modal-content',
  templateUrl: './custom-modal.component.html'
})
export class CustomModal implements OnInit, CloseGuard, ModalComponent<CustomModalContext> {
  context: CustomModalContext;
  form: FormGroup;

  public wrongAnswer: boolean;

  constructor(public dialog: DialogRef<CustomModalContext>, private fb: FormBuilder) {
    this.context = dialog.context;
    this.wrongAnswer = true;
    dialog.setCloseGuard(this);
  }

  ngOnInit() {
    this.form = this.fb.group({
      'clientName': ['', [Validators.required, ValidationService.isAlphabetNSpace]],
      'hospitalGroup': ['', [Validators.required, ValidationService.isAlphabetNSpace]],
      'addressLineOne': ['', Validators.required],
      'addressLineTwo': ['', Validators.required],
      'city': ['', Validators.required],
      'state': ['', Validators.required],
      'postalCode': ['', Validators.required],
      'deployment': ['', Validators.required],
      'details':this.fb.array([
        this.initDetails()
      ])
    });
  }

  initDetails(){
    return this.fb.group({
          'name':[''],
          'jobTitle':[''],
          'email':[''],
          'systemRole':[''],
          'phoneNumber':['']
        });
  }
  addDetail(){
    const control = <FormArray>this.form.controls['details'];
    control.push(this.initDetails());
  }

  removeDetail(i:number){
    const control = <FormArray>this.form.controls['details'];
    control.removeAt(i);
    console.log(this.form.value)
  }

  onKeyUp(value) {
    this.wrongAnswer = value != 5;
    this.dialog.close();
  }


  beforeDismiss(): boolean {
    return true;
  }

  beforeClose(): boolean {
    return this.wrongAnswer;
  }
}

HTML代码

<form [formGroup]="form">
            <wizard-container>
                <wizard-section title="Account Information">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="form-group">
                                <label>Client Name *</label>
                                <input id="clientname" maxlength="100" formControlName="clientName" type="text" class="form-control required">
                                <control-messages [control]="form.controls.clientName"></control-messages>
                            </div>
                            <div class="form-group">
                                <label>Hospital Group *</label>
                                <input id="hospitalgroup" maxlength="100" formControlName="hospitalGroup" type="text" class="form-control required">
                                <control-messages [control]="form.controls.hospitalGroup"></control-messages>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>Address</label>
                                <input id="address1" maxlength="60" formControlName="addressLineOne" type="text" class="form-control required">
                                <control-messages [control]="form.controls.addressLineOne"></control-messages>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>Address</label>
                                <input id="address2" maxlength="60" formControlName="addressLineTwo" type="text" class="form-control required email">
                                <control-messages [control]="form.controls.addressLineTwo"></control-messages>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>City</label>
                                <input id="city" maxlength="100" formControlName="city" type="text" class="form-control required">
                                <control-messages [control]="form.controls.city"></control-messages>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group">
                                        <label>State</label>
                                        <input id="state" maxlength="20" formControlName="state" type="text" class="form-control required email">
                                        <control-messages [control]="form.controls.state"></control-messages>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="form-group">
                                        <label>Postal Code</label>
                                        <input id="postalcode" maxlength="5" formControlName="postalCode" type="text" class="form-control required email">
                                        <control-messages [control]="form.controls.postalCode"></control-messages>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>Deployment *</label>
                                <input id="deployment" formControlName="deployment" type="text" class="form-control required email">
                                <control-messages [control]="form.controls.deployment"></control-messages>

                            </div>
                        </div>
                    </div>
                </wizard-section>
                <wizard-section title="Module Selection">
                    <p>YYPOYOYOYOYYYOYOY</p>
                </wizard-section>
                <wizard-section title="Create Admin">
                    <div formArrayName="details">
                        <div *ngFor="let detail of form.controls.details.controls; let i=index">
                            <div class="panel-body" [formGroupName]="i">
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>Name *</label>
                                        <input id="name" type="text" formControlName="name" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>Job Title *</label>
                                        <input id="name" type="text" formControlName="jobTitle" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>Email *</label>
                                        <input id="name" type="text" formControlName="email" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>System Role *</label>
                                        <input id="name" type="text" formControlName="systemRole" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>Phone Number *</label>
                                        <input id="name" type="text" formControlName="phoneNumber" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <button (click)="removeDetail(i)" *ngIf="form.controls.details.controls.length>1">Delete</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group">
                            <button class="btn btn-primary pull-right" (click)="addDetail()">Add Details</button>
                        </div>
                    </div>
                </wizard-section>
            </wizard-container>
        </form>

请帮助我了解在何处以及如何将表单与后端数据绑定.考虑数据来自服务.(我已经知道如何编写服务只有数据预填充是一个问题)

最佳答案
要预先填充数据,FormGroup实例有两种方法. setValue& patchValue.从服务器收到响应后,只需使用这些方法之一设置/修补值

this.form.patchValue(YOUR_SERVER_RESPONSE);

要了解setValue()和patchValue()之间的区别,请阅读:FormGroup.

转载注明原文:如何预先填充Angular 2中的数据?使用FormGroup? - 代码日志