Home > Software engineering >  How can display/retrieve my database data in reactive form array in angular 12
How can display/retrieve my database data in reactive form array in angular 12

Time:09-18

Hi i have created a form array and sent data to database successfully in angular 12 but i don't know how can retrieve/display that data from data base in same form array, which should be editable ,here i m using modal for data source for explaining ,can any one help me out it is very importent for me, thanks in advance here my stackblitz link

https://stackblitz.com/edit/angular-ivy-xuamdh?file=src/app/app.component.html

<div >
  <form [formGroup]="members">
    <ng-container formArrayName="member" *ngFor="let o of member.controls; let i = index">
      <h2>Member {{ i   1 }}</h2>
      <div [formGroupName]="i" >
        <div >
          <label for="" >1.Name</label>
          <div >
            <input type="text"  formControlName="memberName"/>
          </div>
        </div>
        <div >
          <label for=""  >2. Relation With Applicant</label>
          <div >
            <input type="text"  formControlName="relation"/>
          </div>
        </div>
        <div >
          <label >3.PAN</label>
          <div >
            <input type="text"  formControlName="pan" />
          </div>
        </div>
        <div >
          <label  >4. Aadhar(uid) Number</label>
          <div >
            <input type="text"  formControlName="aadhar"/>
          </div>
        </div>
        <div >
          <label for=""  >5. Residential/Registered Address</label>
          <div >
            <input type="text"   formControlName="address" />
          </div>
        </div>
        <div >
          <button type="button" (click)="removeMembers(i)" >
            <i >&nbsp;Remove</i>
          </button>
        </div>
      </div>
    </ng-container>
  </form>
  <button type="button"  (click)="addMembers()" > Add Member </button>
</div>

ts

constructor(private fb: FormBuilder, private database: DatabaseData) {}
  myData: any = [];
  ngOnInit(): void {
    this.createMember();
    this.myData = this.database.member;
    console.log('database data', this.myData);
  }
  members!: FormGroup;
  createMember() {
    this.members = this.fb.group({
      member: this.fb.array([this.memberForm()]),
      mobile: new FormControl('', [Validators.required]),
    });
  }

  memberForm() {
    return this.fb.group({
      memberName: ['', Validators.required],
      relation: ['', Validators.required],
      pan: ['', Validators.required],
      aadhar: ['', Validators.required],
      address: ['', Validators.required],
    });
  }
  get member() {
    return this.members.get('member') as FormArray;
  }
  addMembers() {
    this.member.push(this.memberForm());
  }
  removeMembers(i: number) {
    this.member.removeAt(i);
  }
}
}

database.ts

export class DatabaseData {
  member: any = [
    {
      memberName: 'Manoj kumar sahni',
      aadhar: '123456789123',
      address: 'bhopal',
      pan: 'cteps0613l',
      relation: 'self',
    },
    {
      memberName: 'Manoj kumar sahni',
      aadhar: '123456789123',
      address: 'bhopal',
      pan: 'cteps0613l',
      relation: 'self',
    },
  ];
}

CodePudding user response:

TLDR: here is a link to a working version of what you are looking for

Based on your code it does not appear that you are using FormArray but rather FormGroup. it seems that you are using a FormGroup that has nested FormGroups. that's perfectly fine, just clarifying.

// this defined a FormGroup
members!: FormGroup;

The form patchValue and setValue offer a simple way to update a FormGroup. you can read more about these two methods in the official docs here

Using this you could update your the method that fetches data from the back end to update your members formGroup as follows

this.members.patchValue({
  memberName: 
})

you were pulling values from your datastore, but never populating the FormGroups.

NOTE: you were also creating a mobile FormControl that was outside the FromGroup. that seemed odd, so I moved it into the standard form. but feel free to move it as you need to.

Here is the updated code:

export class AppComponent {
  name = 'Angular '   VERSION.major;
  constructor(private fb: FormBuilder, private database: DatabaseData) {}
  myData: MemberInfo[] = [];
  ngOnInit(): void {
    this.addMember();
    this.myData = this.database.member;
    // populate existing formGroup for a user or creat new form group if needed
    this.myData.forEach((memberDetails: MemberInfo, index: number) => {
      // add a new form Group each member in returned data if one does not already exist
      if (!this.members.controls[index]) {
        this.addMember();
      }
      // patch the FormGroup with the data from the server.
      this.members.controls[index].patchValue(memberDetails);
    });
    console.log('database data', this.myData);
  }
  memberForm: FormGroup = new FormGroup({
    members: new FormArray([]),
  });

  get members(): FormArray {
    return this.memberForm.get(`members`) as FormArray;
  }

  /** renamed method to be more descriptive */
  getMemberForm() {
    return this.fb.group({
      memberName: ['', Validators.required],
      relation: ['', Validators.required],
      pan: ['', Validators.required],
      aadhar: ['', Validators.required],
      address: ['', Validators.required],
      mobile: ['', Validators.required],
    });
  }

  getMember(i: number): FormGroup {
    return this.members.get(`${i}`) as FormGroup;
  }

  /** Add a new formGroup to existing formArray */
  addMember() {
    this.members.push(this.getMemberForm());
  }

  /** remove a member form group at the designated index */
  removeMember(i: number) {
    this.members.removeAt(i);
  }
}

additionally, your template HTML needed some adjustments. Angular requires that a FormArray be defined within a [FormGroup]. however you were referencing the formArray as the FormGroup

here are the relevant changes

<form [formGroup]="memberForm">
    <div formArrayName="members">
      <div *ngFor="let member of members.controls; index as i">
        <h2>Member {{ i   1 }}</h2>
        <div [formGroupName]="i" >

based on my tests, the app.component creates as many formGroups for each member in your datastore, adding & removing controls manually also works.

This should be enough to get you going, but I would suggest reviewing the official documentation on this top.

good luck.

  • Related