角反应形式在递归ng模板中应用时不将数据绑定到内部子代

时间:2020-03-23 14:22:13

标签: angular recursion ng-template

我的目标是创建一个用户界面,用户可以在其中轻松为其在线商店创建类别和子类别。 为了允许用户创建不确定的子类别,我使用了递归ng-template。

<form [formGroup]="testForm">

<mat-form-field>
  <mat-label class="fontSub">Title</mat-label>
  <input type="text" formControlName="label" matInput>
</mat-form-field>
<mat-form-field>
  <mat-label class="fontSub">Description</mat-label>
  <input type="text" formControlName="desc" matInput>
</mat-form-field>

<div formArrayName="subCategories">

  <ng-template #recursiveList let-subCategories>

    <div style="margin-right: 20px; border-right: 1px solid orange;" *ngFor="let item of subCategories;let i=index;">
      <div [formGroupName]="i">

        <mat-form-field>
          <mat-label class="fontSub">Title</mat-label>
          <input type="text" formControlName="label" matInput>
        </mat-form-field>

        <mat-form-field>
          <mat-label class="fontSub">Description</mat-label>
          <input type="text" formControlName="desc" matInput>
        </mat-form-field>
      </div>
      <!-- {{item.get('element')?.controls?.length}} -->
      <div *ngIf="item.get('subCategories')?.controls?.length > 0">
        <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.get('subCategories').controls }">
        </ng-container>
      </div>
    </div>
  </ng-template>

  <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: testForm.get('subCategories').controls }">
  </ng-container>

</div>

,然后在ngOnInit()中按以下方式初始化testForm:

this.testForm = this.fb.group({
  label:[''],
  desc:[''],
  subCategories: this.fb.array([
    this.fb.group({
      label:[''],
      desc:[''],
      subCategories: this.fb.array([
        this.fb.group({
          label:[''],
          desc:[''],
          subCategories: this.fb.array([
          ])
        })
      ])
    })
  ])
})

尽管模板正确显示并显示了所有子类别,但是当我尝试编辑最内部的控件时,它不会更新,而是我键入的文本正在更新第二级控件。 例如,当我在最里面的对象的desc框中键入内容时,将更新testForm第一个孩子的desc控件。

如果有人可以用这种递归方法帮助我,我会很高兴。

0 个答案:

没有答案
相关问题