[英]add dynamic reactive form groups in angular 2
我有一个具有回复功能的消息服务。 此回复功能特定于用户要回复的消息组。 我需要在打字稿和模板中动态添加表单验证,并在构造函数内部的表单生成器周围进行某种循环,然后如何将mailData.length值传递回构造函数? 我已经在网上尝试了角度教程和其他一些教程,但是没有运气。
// mail.component.ts
constructor(fb: FormBuilder) {
this.MailForm = fb.group({
"content": [null, Validators.compose([Validators.required, /*other validation*/])]
});
}
sendMail(mail:any) {
// Send mail
}
然后在mail.html中
<div *ngFor="let item of mailData; let i = index">
// display original messages here
// reply section
<div id="{{i}}">
<form [formGroup]="i.MailForm">
<textarea class="mailContainerTextArea"
[formControl]="i.MailForm.controls['content']">
</textarea>
<!-- Reply button -->
<button class="mailReply" (click)="sendMail(i.MailForm.value)" [disabled]="!MailForm.valid">Send</button>
</form>
</div>
</div>
经过我finllay的大量搜索和尝试后,在线教程仅适应单击之类的事件中添加的元素,而不是根据现有数组数据创建的表单组。 答案基于Scotch-io-nestedForms中的部分
//component
import { FormBuilder, FormGroup, FormArray, Validators } from "@angular/forms";
//other imports FormArray is the important one
export class SomeComponent{
public MailFormArray:FormGroup;
cnstructor(private fb: FormBuilder) {
this.MailFormArray = fb.group({
"reply": fb.array([
this.createForms(),
])
});
}
// generate the array content
createForms() {
return this.fb.group({
"content": [null, Validators.compose([Validators.required, Validators.pattern('[a-z]')])]
});
}
// create dynamic fields by calling this function after json data loaded, and pass in the json data length
addForms(jsonLength) {
for(let i = 0; i < jsonLength; i++){
const control = <FormArray>this.MailFormArray.controls['reply'];
control.push(this.createForms());
}
}
// replyForm
replyForm(theReply) {
console.log(JSON.stringify(theReply));
}
}
然后在模板中
<form [formGroup]="MailFormArray">
<div formArrayName="reply">
<div *ngFor="let key of jsonData; let j = index;">
<div [formGroupName]="j">
<div *ngFor="let item of key;">
<textarea maxlength="255" formControlName="content"></textarea>
<button (click)="replyForm(MailFormArray.controls.reply.controls[j].value)">Send</button>
</div>
</div>
</div>
</div>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.