こんな感じのarray絵を動的に追加できるようにしました

時間もなく、リファクタリングなどもできていませんが、とりあえず動いているコードの概要部分を共有します

必要ない部分も入っていますが、要所は確認できるはずなので、
参考にしてください

// Component部分
  public setting: Setting;
  public files: File[];
  public isNew: boolean = true;
  public user: User;
  public settingForm: FormGroup;
  public detailFormArray: FormArray;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly fileService: FileService,
    private readonly router: Router,
    private readonly authService: AuthService,
    private readonly settingService: SettingService,
    private readonly fb: FormBuilder) {
  }

  public ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      if (params.id === 'new') {
        this.setting = new Setting();
        this.initSettingForm();
      } else {
        this.settingService.findOne(params.id).then((setting: Setting) => {
          this.setting = setting;
        }).catch((e) => {
          console.log(e);
        }).finally(() => {
          this.isNew = false;
          this.initSettingForm();
        });
      }
      this.user = this.authService.user;
      this.fileService.findAll().then((files: File[]) => {
        this.files = files;
      }).catch((err) => {
        console.log(err);
      });
    });
  }

  public initSettingForm() {
    this.settingForm = this.fb.group({
      title: ['', Validators.compose([
        Validators.required,
        Validators.minLength(3),
        Validators.maxLength(320)
      ])
      ],
      fileId: ['', Validators.compose([
        Validators.required,
      ])
      ],
      details: this.fb.array([])
    });
    this.settingForm.controls['title'].setValue(this.setting.title);
    this.settingForm.controls['fileId'].setValue(this.setting.fileId);
    this.settingForm.controls['details'].setValue(this.setting.details);
  }

  public createDetail(): FormGroup {
    // tslint:disable-next-line:new-parens
    return this.fb.group(new SettingDetail);
  }
  public addDetail() {
    this.detailFormArray = this.settingForm.get('details') as FormArray;
    this.detailFormArray.push(this.createDetail());
  }


// html
<div class="row m-5">
    <div class="col-12" *ngIf="settingForm">
        <form [formGroup]="settingForm" class="text-center border border-light p-5">
            <p class="h4 mb-4">{{isNew ? '設定を追加' : '設定の更新'}}</p>
            <label class="col-form-label">タイトル</label>
            <input name="title" formControlName="title" type="text" class="form-control mb-4" placeholder="後ろに文字入れる">
            <label class="col-form-label">対象ファイル</label>
            <select formControlName="fileId" class="form-control form-control mb-4">
                <option *ngFor="let file of files" [value]="file.id">{{file.filename}}</option>
            </select>
            <button class="btn btn-primary" (click)="addDetail()">追加</button>

            <p class="h4 mb-4">設定の詳細設定</p>
            <div formArrayName="details">
                <div *ngFor="let detail of ValueFormControl.controls; let i = index;" [formGroupName]="i">
<!--                    <label class="col-form-label">ターゲットカラム</label>-->
                    <input formControlName="targetColumn" type="text" class="form-control mb-4" placeholder="対象のカラム">
<!--                    <label class="col-form-label">Start word</label>-->
                    <input formControlName="startWord" type="text" class="form-control mb-4" placeholder="どこから開始?">
<!--                    <label class="col-form-label">End word</label>-->
                    <input formControlName="endWord" class="form-control mb-4" placeholder="どこで終わる?">
                </div>
            </div>
            <button type="submit" class="btn btn-info btn-block my-" (click)="onSubmit()" [disabled]="!settingForm.valid">情報更新</button>
        </form>
    </div>
</div>

参考記事

Angular 2 Cannot find control with unspecified name attribute on formArrays
Dynamically adding form fields using Angular formArray
Adding to the FormArray Dynamically

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA