首页 > 解决方案 > 连接

  • 带有 formControlName 的标签,使用 Reactive Forms 的 FormBuilder
  • 问题描述

    我正在使用反应形式从输入中获取数据。它工作正常,但是我不得不从ul & li的 html 标签中获取所选选项的值

    我使用了与输入值相同的方法,但现在出现错误。

    研究时,我知道 formControlName 不能在li中使用

    问题:解决这个问题的方法是什么?我应该选择选择选项,还有其他方法吗?

    .ts 文件

    this.filtersForm = this.fb.group({
      budgetPrice: this.fb.group({
        gte: '',
        lte: ''
      }),
      parcelArea: this.fb.group({
        gte: '',
        lte: ''
      }),
      accommodationArea: this.fb.group({
        gte: '',
        lte: ''
      }),
      accommodationBedrooms: this.fb.group({
        eq: ''
      })
    });
    
    this.filtersForm.valueChanges
    .pipe(debounceTime(1000))
    .subscribe(e => {
      this.filterCriteriaChanged.emit(this.filtersParam(e));
      console.log('filter: ',e)
    });
    

    .html 文件

    <form [formGroup]="filtersForm">
    <div formGroupName="accommodationBedrooms">
    <ul class="noOfItems" formControlName="eq">
    <li *ngFor="let bedroom of bedrooms" [value]="bedroom.value" (click)="onSelectValue($event)">{{ bedroom.value }} </li>
    </ul>
    </div>
    </form>
    

    错误

    带有路径的表单控件没有值访问器:'accommodationBedrooms -> eq

    标签: htmlangularangular-reactive-formsformgroups

    解决方案


    您可以创建一个包装您的 ul / li 的组件。当此组件实现 ControlValueAccessor 接口时,它可以像任何其他“输入”字段一样运行,支持 formControlName 指令。

    您可以按照此说明进行操作。


    推荐阅读