【问题标题】:Must supply a value for form control at index: 1 - Error必须在索引处为表单控件提供一个值:1 - 错误
【发布时间】:2019-02-12 22:53:30
【问题描述】:

我正在使用带有 mat 自动完成功能的反应式表单。我在我的应用程序的其他部分使用了自动完成功能,但我无法弄清楚。我有一个formarray,每次我想在我的情况下添加一个新传感器时都会添加一个输入。自动完成在我的第一个输入中工作正常,但是当我尝试添加更多输入时显示错误:错误:必须在索引处为表单控件提供值:1

HTML:

<div class="row">
    <div class="input-field col s10">
      <div class="form-group">
        <div formArrayName="sensors_id">
          <div *ngFor="let sensor of addHomeboxPForm.get('sensors_id')['controls']; let i = index">
            <br>
            <input formControlName="{{i}}" type="text" placeholder="Select Sensor" aria-label="Number" matInput [matAutocomplete]="auto1">
            <mat-autocomplete autoActiveFirstOption #auto1="matAutocomplete" [displayWith]="displayWith" >
              <mat-option (onSelectionChange)="updateForm($event, [sensor.sensors_id], 'sensors_id')" *ngFor="let sensor of filteredOptionsS | async" [value]="sensor.sensor_serial">
                {{sensor.sensor_serial}}
              </mat-option>
            </mat-autocomplete>
            <div class="button-left">
              <button *ngIf="addHomeboxPForm.controls.sensors_id.value.length > 1" type="button" class="fa" (click)="onRemoveItem(i)">RemoveSensor</button>
            </div>
          </div>
        </div>
      </div>


<div class="input-field col s2">
        <button type="button" class="btn" (click)="onAddItem()">AddSensor</button>
      </div>

TS:

表单数组:'sensors_id': this.fb.array([], Validators.required),

  updateForm(ev: any, idd: any, componentid: any) {

    if (ev.isUserInput) {
      if (componentid === 'sensors_id') {
        this.sensorId = idd;
        this.addHomeboxPForm['controls']['sensors_id'].setValue([ev.source.value])
      }
    }
  }

  onAddItem() {
    (<FormArray>this.addHomeboxPForm.controls['sensors_id']).push(new FormControl('', Validators.required));
  }

  onRemoveItem(index: number) {
    (<FormArray>this.addHomeboxPForm.controls['sensors_id']).removeAt(index);
  }

我是新手,如果我不是很清楚,我很抱歉..但我还没有找到解决方案

【问题讨论】:

    标签: angular angular-reactive-forms formarray mat-autocomplete


    【解决方案1】:

    在模板 html 中使用之前,应该在组件中定义你的 fortmcontrolName。

    我看到你使用了&lt;input formControlName="{{i}}",这是无效的,因为 Angular 无法找到最初声明反应表单的这个 formControl/字段。

    在组件类中创建控件后,必须将其与模板中的表单控件元素相关联。使用 ReactiveFormsModule 中包含的 FormControlDirective 提供的 formControl 绑定更新带有表单控件的模板。

    你可以阅读更多关于reactive forms here:

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      此错误可能是因为您忘记将 setValue 函数设置为数组,而是将其设置为对象(注意括号 []):

      示例: 在这里你会得到错误。错误:

      this.checkoutForm.get('items').setValue({
        itemId: ['1aa'],
        itemName: ['2aa'],
        itemDesc: ['3bb'],
        itemDone: ['', Validators.requiredTrue]
      });
      

      对:

      this.checkoutForm.get('items').setValue([{
        itemId: ['1aa'],
        itemName: ['2aa'],
        itemDesc: ['3bb'],
        itemDone: ['', Validators.requiredTrue]
      }]);
      

      html:

      <div class="form-group">
              <label for="exampleInputPassword1">Items</label>
              <div class='col-sm-10' formArrayName="items">
                  <div *ngFor="let item of checkoutForm.controls.items['controls']; let i=index" [formGroupName]="i">
                      <a [routerLink] (click)="removeitem(i)">remove</a>
                      <input class="form-control" type="text" formControlName="itemId" id=task{{i}}>
                      <input class="form-control" type="text" formControlName="itemName" id="task{{i}}">
                      <input class="form-control" type="text" formControlName="itemDesc" id="task{{i}}">
                      <input type="checkbox" formControlname="itemDone">Mark as Done
                  </div>
              </div>
          </div>
      

      【讨论】:

        【解决方案3】:

        更新时,使用 patchValue() 方法代替 setValue() 方法。

        在你的情况下,它将是 -

            updateForm(ev: any, idd: any, componentid: any) {
        
            if (ev.isUserInput) {
              if (componentid === 'sensors_id') {
                this.sensorId = idd;
                this.addHomeboxPForm['controls']['sensors_id'].patchValue([ev.source.value])
              }
            }
          }
        
          onAddItem() {
            (<FormArray>this.addHomeboxPForm.controls['sensors_id']).push(new FormControl('', Validators.required));
          }
        
          onRemoveItem(index: number) {
            (<FormArray>this.addHomeboxPForm.controls['sensors_id']).removeAt(index);
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-24
          • 2018-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-11
          • 2018-10-23
          相关资源
          最近更新 更多