2016-11-01 39 views
3

formBuilder.arrayに配列の値を設定する際に問題があります。配列ではないformBuilderでは、この方法でsetValueを使用できますが、formBuilder.arrayではできません。私はformbuilder 'listServiceFeature'と 'listservicefeature'に値を設定しようとしましたが、どちらの方法でも値が設定されていません。それはあなたが何をしたいかのように私には見えますformbuilder配列の値を設定する方法

TS

listServiceFeature: any = ['m1', 'm2'] 

contentFormValidate(): void { 

    this.contentForm = this.formBuilder.group({ 
      'listservicefeature': this.formBuilder.array([ 
       this.formBuilder.group({ 
       listServiceFeature: ['', [Validators.required] 
       }); 
      ]), 
    }); 

    this.contentForm.controls['listservicefeature'].setValue(this.listServiceFeature); 
} 


addServiceFeature() { 
    const control = <FormArray>this.contentForm.controls['listservicefeature']; 
    control.push(this.initServiceFeature()); 
} 

removeServiceFeature(i: number) { 
    const control = <FormArray>this.contentForm.controls['listservicefeature']; 
    control.removeAt(i); 
} 

HTML

<div formArrayName="listservicefeature"> 
    <div class="form-group" *ngFor="let servicefeature of contentForm.controls.listservicefeature.controls; let i=index"> 
    <label for="Service">Features {{i+1}}</label> 
    <div class="input-group" [formGroupName]="i"> 
     <input type="text" class="form-control" formControlName="listServiceFeature"> 
     <template [ngIf]="i == 0"> 
      <span class="input-group-btn"> 
      <button (click)="addServiceFeature()" class="btn btn-default" type="button"> 
      <span class="lnr lnr-plus-circle icon-orange-gable-buttom"></span> 
      </button> 
      </span> 
     </template> 
     <template [ngIf]="i > 0"> 
      <span class="input-group-btn"> 
      <button (click)="removeServiceFeature(i)" class="btn btn-default" type="button"> 
      <span class="lnr lnr-trash icon-orange-gable-buttom"></span> 
      </button> 
      </span> 
     </template> 
    </div> 
    </div> 
</div> 

答えて

0

はformArrayにコントロールを追加することです。 反応-フォーム

のドキュメントを見てみましょう

https://angular.io/guide/reactive-forms

引用:あなたがいないのsetValueで、FormGroup.setControl方法で、以前のFormArrayを置き換える

注意してください。あなたはコントロールの値ではなく、コントロールを置き換えています。 1)formArrayへのショートカットとしてゲッターを追加します:

get listservicefeatures(): FormArray { 
    return this.contentform.get('listservicefeature') as FormArray; 
    }; 

2)のようになりaddメソッドを作成:

addServiceFeature() { 
this.listservicefeatures.push(this.fb.group({newservicefeature: 'defaultvalue', [Validators.required]})); 
} 
を、彼らはこのように行うドキュメントの

また、formArrayの宣言は次のようになります。

this.contentForm = this.formBuilder.group({ 
      'listservicefeature': this.formBuilder.array([]), 
    }); 

私はこれが役に立ちそうです:)

関連する問題