Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-populate for data in Angular 2? Using FormGroup?

I am building a form in Angular 2. The process of building the form for submission is straight forward but I also need an edit feature. My problem is that I dont understand how to pre-populate the data in the form from the Backend. I do have a backend service and I am getting data from it. But I have no clue how this data will bind to the existing form.

The code for the form is as follows:-

Component code

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 Code

<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>

Please help me to understand where and how can I bind the form with the backend data. Consider the data is coming from a service.(I already know how to write a service only data pre-population is a problem)

like image 800
Shiv Kumar Ganesh Avatar asked Feb 08 '17 05:02

Shiv Kumar Ganesh


2 Answers

To pre-populate data there are two methods of FormGroup instance. setValue & patchValue. After you receive the response from server just set/patch the values using one of these methods

this.form.patchValue(YOUR_SERVER_RESPONSE);

To know the difference between setValue() and patchValue() read here: FormGroup.

like image 150
Sabbir Rahman Avatar answered Oct 02 '22 17:10

Sabbir Rahman


You are currently building the "form" with empty quotes. To pre-populate the form, replace those with the data you want to use instead. Like so:

export class CustomModal implements OnInit, CloseGuard, ModalComponent<CustomModalContext> {
  context: CustomModalContext;
  form: FormGroup;

  public wrongAnswer: boolean;

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

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

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

  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;
  }
}
like image 34
James Avatar answered Oct 02 '22 16:10

James