繁体   English   中英

Angular 反应式 Forms - FormArray 和 pacthValue

[英]Angular Reactive Forms - FormArray and pacthValue

我在使用带有 formArray 的 patchValue 时遇到问题。 我有一个用<ul><li>制作的自定义 select ,单击一个选项会执行一个方法,该方法应该修补在<input type="hidden" />中选择的选项的 ID,该选项将包含表单数组中的属性。

这是表单的构建方式:

  this.roleForm = this.fb.group({
    profiles: this.fb.array([ this.fb.group({perfil: '', accion: ''}) ])
  })

这是在数组中添加新配置文件的方法:

  addProfile() {
    const prof = this.roleForm.get('profiles') as FormArray;
    prof.push(this.fb.group({
      perfil: [''],
      accion: ['']
    }))
  }

这是 html:

<div class="col-md-8" formArrayName="profiles">
  <div class="row" *ngFor="let profile of getProfiles(); let i = index">
    <div class="col-md-6" [formGroupName]="i">
      <div class="col-12">
        <div class="card card-primary bg-white">
          <div class="card-header h4">
            Perfil
          </div>
          <ul class="list-group list-group-flush register h5 scroll-list">
            <li *ngFor="let profileType of profileTypes; index as i" 
                class="list-group-item rounded-0 pointer" 
                [ngClass]="{'selected bg-primary text-white font-weight-bold': this.selectedProfile === profileType.profileId}" 
                (click)="selectProfile(profileType.profileId, i)">
              {{profileType.profileDescription}}
            </li>
          </ul>
          <input formControlName="perfil" type="text" />
        </div>
      </div>
    </div>
  </div>
</div>

编辑:

我必须在此方法中使用 patchValue 以在输入中设置具有相同索引的选定值。 但我不能让 at() 方法工作,这总是给我一个未定义的结果:

selectProfile(profileType.profileId, i) {
 let x = (<FormArray>this.roleForm.get('profiles')).at(i);
 console.log(x)
}

我猜你的问题是模板变量i的重复声明:

<div class="col-md-8" formArrayName="profiles">
  <div class="row" *ngFor="let profile of getProfiles(); let outterI = index"> <!-- declared here -->
    <div class="col-md-6" [formGroupName]="outterI">
      <div class="col-12">
        <div class="card card-primary bg-white">
          <div class="card-header h4">
            Perfil
          </div>
          <ul class="list-group list-group-flush register h5 scroll-list">
            <!-- and here -->
            <li *ngFor="let profileType of profileTypes; index as innerI" 
                class="list-group-item rounded-0 pointer" 
                [ngClass]="{'selected bg-primary text-white font-weight-bold': this.selectedProfile === profileType.profileId}" 
                (click)="selectProfile(profileType.profileId, outterI)">
              {{profileType.profileDescription}}
            </li>
          </ul>
          <input formControlName="perfil" type="text" />
        </div>
      </div>
    </div>
  </div>
</div>

使用ngFor时不需要声明索引变量,但如果您不使用它,因为在此示例中您似乎没有使用innerI

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM