2016-12-28 61 views
0

我發現我認爲可能是一個錯誤,但不確定。Angular2中奇怪的formArray行爲

如果我用這個代碼:

<div formArrayName="techs" > 
    <div *ngFor="let tech of techListInFB | async; let i=index">     
    <md-checkbox [formControlName]="i"> 
     {{tech.$key}} - {{tech.name}} 
    </md-checkbox> 
    </div> 
</div> 

我得到這個錯誤,我的應用程序崩潰:

Cannot find control with path: 'techs -> 0' 

但是,如果我在組件模板的任意位置添加這一行:

{{techListInFB | async}} 

一切工作正常。那麼這條線怎麼可能消除這個錯誤呢?我沒有看到該線路正在做什麼來改變任何事情。

+0

你能告訴我們你是如何獲取techListInFB? – silentsod

回答

0

我對嵌套模型驅動窗體沒有多少經驗,但是我找到了一些資源。

繼承人的通過實例的香餑餑:

<div formArrayName="addresses"> 
     <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default"> 
     <div class="panel-heading"> 
      <span>Address {{i + 1}}</span> 
      <span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)"></span> 
     </div> 
     <div class="panel-body" [formGroupName]="i"> 
      <div class="form-group col-xs-6"> 
      <label>street</label> 
      <input type="text" class="form-control" formControlName="street"> 
      <small [hidden]="myForm.controls.addresses.controls[i].controls.street.valid" class="text-danger"> 
       Street is required 
      </small> 
      </div> 
      <div class="form-group col-xs-6"> 
      <label>postcode</label> 
      <input type="text" class="form-control" formControlName="postcode"> 
      </div> 
     </div> 
     </div> 
    </div> 

和控制器:

public myForm: FormGroup; 

    constructor(private _fb: FormBuilder) { } 

    ngOnInit() { 
     this.myForm = this._fb.group({ 
      name: ['', [Validators.required, Validators.minLength(5)]], 
      addresses: this._fb.array([ 
       this.initAddress(), 
      ]) 
     }); 
    } 

    initAddress() { 
     return this._fb.group({ 
      street: ['', Validators.required], 
      postcode: [''] 
     }); 
    } 

    addAddress() { 
     const control = <FormArray>this.myForm.controls['addresses']; 
     control.push(this.initAddress()); 
    } 

    removeAddress(i: number) { 
     const control = <FormArray>this.myForm.controls['addresses']; 
     control.removeAt(i); 
    } 

plnkr with working relatively complex formswhich comes from here.

我想看到你的組件/控制器太