在angular 2中添加动态响应式表单组
add dynamic reactive form groups in angular 2
我有一个具有回复功能的消息服务。此回复功能特定于用户想要回复的消息组。我需要在typescript和模板中动态添加表单验证,在构造函数中围绕表单构建器进行某种循环,然后我如何传递mailData。长度值返回构造函数?我已经尝试了angular教程和其他一些在线,但没有运气。
// mail.component.ts
constructor(fb: FormBuilder) {
this.MailForm = fb.group({
"content": [null, Validators.compose([Validators.required, /*other validation*/])]
});
}
sendMail(mail:any) {
// Send mail
}
then in 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>
经过大量的搜索和播放,我终于得到了它,在线教程只迎合添加元素的事件,如点击,而不是基于现有数组数据创建的形式组。答案是基于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>
相关文章:
- 如何创建对表单的自我更新响应
- 使用yii2表单等待ajax响应
- 引导表单向导 - 防止在提交 ajax 响应的每个页面表单出现错误时滚动到下一步
- 如何在 JavaScript 中对表单帖子的响应做出反应
- 提交表单时在弹出窗口中打开响应
- 使用php提交表单,并使用ajax向用户提供响应
- 通过响应按钮单击更改表标题,其中行使用 JSTL for 循环更新
- 异步表单w/Iframe Target——OnLoad适用于FF、Chrome、IE9,不适用于;无法在IE7中得到响应
- 在同一个html页面中显示servlet响应而不隐藏表单
- 使用AJAX提交登录表单并获得响应
- 谷歌表单:将项目添加到响应中
- 如何在java框架(JSF)中基于URL的json响应生成动态表单
- 如果我使用html表单(而不是ajax),则获取服务器的响应代码或返回值
- AJAX表单,通过JSON响应进行php验证
- 表单验证Javascript没有响应
- 移动响应表单不起作用
- 在 ruby 中自动填写、提交和审查 JavaScript 表单的响应
- 如何使用XMLHttpRequest获取响应表单servlet
- 以编程方式添加处理程序来响应表单处理程序
- 如何获得json响应表单parse.com使用query.find();在web应用中使用javascript