Filout
Filout

Reputation: 101

*ngFor with sub array

(Sorry for this subject, but I don't think much of anything else)

Hi there, i get JSON datas in the following way:

{
(... some stuff...)

"credentials": {
    "credential": [{
        "username": "Peter",
        "password": "dummy1"
    }, {
        "username": "Marc",
        "password": "dummy2"
    }, {
        "username": "Oliver",
        "password": "dummy3"
    }, {
        "username": "Tom",
        "password": "dummy4"
    }, {
        "username": "Brian",
        "password": "dummy5"
    }]
}

}

and i want to display them with *ngFor like this:

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

@Component({
  selector: 'my-app',
  template: `
    <form [formGroup]="form">
      <input type="checkbox" formControlName="published"> Published
      <div *ngIf="form.controls.published.value">

        <h2>Credentials</h2>
        <button (click)="addCreds()">Add</button>

        <div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value; let i = index">
          <ng-container [formGroupName]="i">
            <input placeholder="Username" formControlName="username">
            <input placeholder="Password" formControlName="password">
          </ng-container>
        </div>

      </div>
    </form>
  `,
})
export class AppComponent  {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      published: true,
      // credentials: {credential: new FormArray([])}
      credentials: {credential: this.fb.array([])}
    });
  }

  addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    // const creds = this.form.controls.credentials.value.credential as FormArray;
    creds.push(this.fb.group({
      username: '',
      password: '',
    }));
  }
}

But this doesn't work. :-( Q: How can i display all credentials with *ngFor? Important for me ist only *ngFor in this case.

Thank you in advance and greetings Filout

Upvotes: 1

Views: 390

Answers (1)

FedG
FedG

Reputation: 1301

Write in ts.

this.form = this.fb.group({
  published: true 
  credentials: this.fb.array([])}
});

 get credentials() {
      return this.form.get('credentials') as FormArray

In html

*ngFor="let creds of credentials?.controls; ......

Upvotes: 1

Related Questions