[英]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.