简体   繁体   English

角反应形式验证* ngFor中的动态形式

[英]Angular Reactive form Validation for dynamic forms inside *ngFor

I am new to angular when I was trying to put the form validation to the text field form was present inside *ngFor loop, So validation is working but it shows to every field but I want validation the particular field only , so please help me How to put the validation to the particular form field. 当我尝试对*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)]]
    });
  }

Your posts all share the one and same form. 您的posts都共享一个相同的表格。 If you have n amount of posts , you need n amount of forms. 如果您有n posts ,则需要n个表格。 We can achieve this by creating an array (just a JS array) of formgroups, the same length that your posts array is... 我们可以通过创建一个表单组数组(只是一个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)])
    }))
  })
}

Then in your template you iterate formsArr . 然后,在您的模板中,迭代formsArr You probably need access to some stuff in your posts array... so we add the index in iteration, therefore you can access the specific post with posts[i] . 您可能需要访问posts数组中的某些内容...因此我们在迭代中添加了索引,因此您可以使用posts[i]访问特定的post Also remove method="post" from your form: 同时从您的表单中删除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>

StackBlitz StackBlitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM