node.js - *ngFor 中动态表单的 Angular 反应式表单验证
问题描述
当我试图将表单验证放入*ngFor
循环中的文本字段表单时,我是新来的,所以验证正在工作,但它显示给每个字段,但我只想验证特定字段,所以请帮助我如何放置对特定表单字段的验证。
**HTML**
<div class="container" *ngFor="let post of posts; let i = index">
<div class="row">
<div class="col-md-12" style="display: block; ">
<form [formGroup]="commentForm" method="post" enctype="multipart/form-data" (ngSubmit)="comment_Submit(post.user_id, post.post_id,
commentForm)">
<div class="form-group">
<input type="text" class="form-control" name="comment{{i}}" formControlName="comment" id="comment"
placeholder="Enter comments" cols="40" rows="5" spellcheck="true"
style="width:100%; height: auto; border: 1px solid #ada5a5; border-radius: 4px; outline: none; user-select: text; white-space: pre-wrap; overflow-wrap: break-word; "
[ngClass]="{'form-control': true,
'is-invalid': !f.comment.valid,
'is-valid':f.comment.valid}">
<div *ngIf="f.comment.errors?.minlength && f.comment.touched" class="text-danger">Comment
should be at
least 2 characters.</div>
</div>
<button type="submit" class="btn-sm btn-success" [disabled]="!commentForm.valid">Comment</button>
</form>
</div>
</div>
</div>
**TypeScript**
export class PostsComponent implements OnInit {
get f() { return this.commentForm.controls; }
constructor(private userService: UserService, private formBuilder: FormBuilder,
private alerts: AlertsService) {
this.commentFormValidation();
}
commentForm: FormGroup;
ngOnInit() { }
commentFormValidation() {
this.commentForm = this.formBuilder.group({
comment: [null, [Validators.required, Validators.minLength(2)]]
});
}
解决方案
你们posts
都共享一个相同的表格。如果你有n
数量posts
,你需要n
数量的表格。我们可以通过创建一个表单组数组(只是一个 JS 数组)来实现这一点,它的长度与您的posts
数组相同......
formsArr = [];
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.posts.forEach((x) => {
this.formsArr.push(this.fb.group({
comment: this.fb.control('', [Validators.required, Validators.minLength(2)])
}))
})
}
然后在您的模板中进行迭代formsArr
。您可能需要访问posts
数组中的某些内容......所以我们在迭代中添加索引,因此您可以post
使用posts[i]
. 还要method="post"
从您的表单中删除:
<div *ngFor="let a of formsArr; let i = index">
<form [formGroup]="a" (ngSubmit)="onSubmit(a.value, posts[i].user_id)">
<input formControlName="comment" />
<small *ngIf="a.hasError('minlength', 'comment') && a.get('comment').touched">
Needs to be 2 letters
</small>
<button type="submit" [disabled]="!a.valid">Comment</button>
</form>
</div>
推荐阅读
- javascript - 在遍历数组时创建对象
- ios - Safari 无法打开页面,因为地址无效
- html - 如何对齐图像中心的文本
- spring - Couchbase 过滤器查询 -> 使用 Spring Data Couchbase(SpEL 表示法)在两个数字之间范围内的数字。)
- r - RStudio notebook,knitr,从包生成的html输出和从笔记本生成的word文件
- node.js - 下载时生成的docx为空
- kubernetes - k8s 如何知道主机上运行的服务?
- java - 我如何用两种不同的方法在同一个文本字段上书写?
- android - SIGABRT 在使用 Android NDK 的 ASAN 中捕获异常
- mongodb - MongoDB - 按内部文档分组并检索最佳结果