[英]Angular Reactive form Validation for dynamic forms inside *ngFor
當我嘗試對*ngFor
循環中存在的文本字段進行表單驗證時,我是*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
數組中的某些內容...因此我們在迭代中添加了索引,因此您可以使用posts[i]
訪問特定的post
。 同時從您的表單中刪除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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.