*ngFor与子数组

问题描述 投票:0回答:1

(对不起,这个话题,我也没什么别的想法)

你好,我用以下方式获取JSON数据。

{
(... some stuff...)

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

}

我想用*ngFor来显示它们,就像这样。

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: '',
    }));
  }
}

但这是行不通的 :-(Q: 我怎样才能显示所有的? credentials 与*ngFor?对我来说,重要的是在这种情况下只有*ngFor。

先谢谢你,问候Filout。

angular ngfor formarray
1个回答
1
投票

写在ts里。

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

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

在html中

*ngFor="let creds of credentials?.controls; ......
© www.soinside.com 2019 - 2024. All rights reserved.