找不到带有路径的控件:“ alternateAddress-> [object Object]”

时间:2019-05-30 23:01:34

标签: angular angular-reactive-forms formarray

我正在使用FormArray将表单组动态添加到表单。当我推送一个新创建的表单组并显示在模板中时,angular很难找到该控件元素的路径。

我已经参考了有关使用表单数组添加动态控件的角度文档。 https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays 以及堆栈溢出中的类似问题:Angular: Cannot find control with path: 'variable-> 0 -> id'

组件类:

get alternateAddress() {
    return this.signupForm.get('alternateAddress') as FormArray;
  }
 buildAddress() {
    return this.fb.group({
      city: [''],
      street: ['']
    });
  }
  addAlternateAddress() {
    this.alternateAddress.push( this.buildAddress());
  }
  ngOnInit() {
    this.signupForm = this.fb.group({
      name: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirmPassword: ['', [Validators.required]],
      email: ['', [Validators.email]],
      subscribe: [''],
      phone: ['', [Validators.required, Validators.pattern]],
      topic: ['', [Validators.required]],
      address: this.fb.group({
        city: [''],
        street: ['']
      }),
      alternateAddress: this.fb.array([ ])
    }, {validator: PasswordMatchValidator});

组件模板

 <button type="button" class="btn btn-sm btn-warning" (click)="addAlternateAddress()">Add alternate address</button>
    <div *ngIf="alternateAddress.length > 0">
      <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
        <div [formGroupName]="alternateAddress.controls[i]">
          <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control" name="city" [formControlName]="city">
          </div>
          <div class="form-group">
            <label for="name">Street</label>
            <input type="text" class="form-control" name="street" [formControlName]="street">
          </div>
        </div>
      </div>
    </div>

我不太确定如何提供形成组的路径并参考文档中的单个控件,仅演示控件部分。

感谢社区投入精力进行调试。

1 个答案:

答案 0 :(得分:0)

感谢developer033的评论。它确实帮助我调试了代码。

    <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
                <div [formGroupName]="i">
<div class="form-group">
                <label for="city">City</label>
                <input type="text" class="form-control" name="city" formControlName="city">
              </div>

这解决了问题。将索引绑定到 [ formGroupName ] ,并使用不带方括号的 formControlName