关于Angular 2中的FormArray

时间:2016-11-21 07:12:49

标签: angular

我正在研究Angular 2应用程序示例,我使用的是ReactiveForms模块。

下面是创建FormGroup,FormControls和FormArray的代码。

//-- create formgroup , Reactive form
this.fg = this.fb.group({
                       "ticketID": [""],
                       "title":["title" ,   Validators.compose([Validators.required , Validators.maxLength(50)])],
                       "description":["description" , Validators.compose([Validators.required , Validators.maxLength(50)])],
                       "projectID":["" , Validators.required],
                       "severityID":["" , Validators.required],
                       "statusID":["" , Validators.required],                           
                       "comments": this.fb.array([
                        this.fb.group({
                                        "commentID": [""], 
                                            "commentDate":[""],
                                            "commentText":["comment text"]      
                                      })
                        ])
                     });

以下是我的模板代码

<form [formGroup]="fg" (ngSubmit)="onSubmit()">
   <input type="text" formControlName="title"><br>
   <input type="text" formControlName="description"><br>      

   <select formControlName="statusID">
<option [value]="status.statusID" *ngFor="let status of statuses | async">
    {{status.statusText}}
</option>
   </select><br>
   <textarea formControlName="????"></textarea><br> 
   <input type="submit" value="Submit1"><input type="button" value="Reset" (click)="onReset()">
</form>

我的问题是如何在html字段下面引用“commentText”formControl

<textarea formControlName="????"></textarea>

1 个答案:

答案 0 :(得分:0)

试试这个:

<textarea [formControl]="fg.get('comments').at(2)"></textarea><br>


//-- create formgroup , Reactive form
this.fg = this.fb.group({
                       "ticketID": [""],
                       "title":["title" ,   Validators.compose([Validators.required , Validators.maxLength(50)])],
                       "description":["description" , Validators.compose([Validators.required , Validators.maxLength(50)])],
                       "projectID":["" , Validators.required],
                       "severityID":["" , Validators.required],
                       "statusID":["" , Validators.required],                           
                       "comments": this.fb.array([
                           new FormControl(),
                           new FormControl(),                    
                           new FormControl("comment text")
                        ])
                     });