Search code examples
angularformstypescriptvalidationngfor

How to bind angular form validation with ngFor


Hello every one i am trying to do comment form validation, For every post there comment box like Facebook, but i am unable to bind the comment form with ngFor index with formControlName="comment", So please anyone help me

I am already tried so many example but nothing will helped me . And i am my code below so check carefully and help me.


<div class="container" style="width: 100%; height: 100%;  ">
  <div class="row" style=" margin: 1px; background-color: #fff; border: 2px solid #ada5a5; border-radius: 4px; ">
    <!-- ngFor for posts -->
    <div class="container" *ngFor="let post of posts; let i = index">
      <!-- {{post.user_id}}, {{post.post_id}}, {{post.saved_name}}, {{ post.file_path}} -->
      <div class="
      row" style="border: 1px solid #e6e6e6;">
        <div class="col-md-12 col-md-offset-0" style=" height: auto; ">
          <h6> {{post.description}} </h6>
        </div>
      </div>
     <div class="row">
        <div class="col-md-12" style="display: block; ">

          <form [formGroup]="commentForm" (ngSubmit)="comment_Submit(post.user_id, post.post_id,
            commentForm )" name="commentForm{{i}}">
            <div class="form-group">
              <input type="text" class="form-control" name="comment{{i}}" formControlName="comment_{{i}}"
                id="comment{{i}}" placeholder="Enter comments" 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}">
              <!-- <span *ngIf="f.comment.errors?.required && f.comment.touched" class="text-danger">Field is required</span> -->
              <div *ngIf="f.comment.errors?.minlength && (f.comment.dirty || f.comment.touched)"
                class="alert alert-danger"> Comment should be at least 2 characters. </div>
            </div>
            <!--<textarea name="Text1" cols="40" rows="5"></textarea> (ngSubmit)="onSubmit(uploadForm)
              <textarea name="comment" form="usrform">Enter text here...</textarea>
              <textarea rows=3 class="form-control form-input" type="text" formControlName="question"></textarea>-->
            <button type="submit" class="btn-sm btn-success" [disabled]="!commentForm.valid">Comment</button>

          </form>  <!---Form End-->

        </div>
      </div>

  </div>
</div>


Typescript Code:

export class PostsComponent implements OnInit {
  // Set server = 'localhost:3000/';
  // apiUrl: string = 'localhost:3000';
  users: User[];
  user_id: string;
  posts: Post[];
  files: File[];
  post_id: any;
  saved_name = [];
  tmp_files = [];

  likes: Like[];
  like_id: number | null ;
  like_status: string;
  postLikes: any;

  comments: Comment[];
  comment_text: string;
  formsArr = [];
  commentForm: FormGroup;

   get f() { return this.commentForm.controls; }

  constructor(private userService: UserService, private http: HttpClient, private formBuilder: FormBuilder, private router: Router,
    private alerts: AlertsService) {
    this.userService.getUser_id()
      .subscribe(
        data => {
          this.user_id = data.toString();
          this.getPosts(this.user_id);
          this.getFiles(this.user_id);
          this.get_likes();
          this.getPostLikes(this.user_id);
          this.get_comments();
          // this.getPostsWithLikes();
        },
        error => this.router.navigate(['/login'])
        // this.router.navigateByUrl('/login');
      );
      this.commentFormValidation();

  }

  ngOnInit() {   }

    commentFormValidation() {
      // debugger
      this.commentForm = this.formBuilder.group({
      comment: ['', [Validators.required, Validators.minLength(2)] ]
     });
  }



  // Get user details from DB
  getPosts(user_id) {
    this.userService.getPosts(user_id).subscribe((data) => {
      this.posts = data;
    },
      error => {
        return console.log(error);
      }
    );
  }


By using above code i am getting validation to every comment box when i touched on one comment box, But i want only one validation to particular comment box which i touched.


Solution

  • You need a different formControlName for each input.

    You can use whatever you want as formControlName .

    I use as formControlName ="comment" + 'the id of the post' -> comment1,comment2...

    Here is the stackblitz: https://stackblitz.com/edit/angular-uteyji

    So you need something like this in html:

    <form [formGroup]="commentForm">
        <div class="form-group">
            <input
                type="text"
                formControlName="comment{{post.post_id}}"
                class="form-control"
                [ngClass]="{
                    'form-control': true,
                    'is-invalid': !f.comment.valid,
                    'is-valid':f.comment.valid
                }"
                placeholder="Enter comments"
                spellcheck="true">
    
            <div *ngIf="checkForError(post)" class="alert alert-danger">
                  Comment should be at least 8 characters. 
            </div>
        </div>
    
        <button type="submit" class="btn-sm btn-success" [disabled]="!commentForm.valid">Comment</button>
    
    </form> 
    

    Component will be like this:

    constructor(private http: HttpClient, private formBuilder: FormBuilder) {
        this.comments = new Array<Comment>();
        this.commentFormValidation();
    }
    
    ngOnInit() {}
    
    commentFormValidation() {
        this.commentForm = this.formBuilder.group({
            comment: ['', [Validators.required, Validators.minLength(8)]]
        });
    
        let i=0;
    
        this.posts.forEach(post => {
            this.commentForm.addControl(
                'comment' + String(post.post_id),
                new FormControl(
                    this.comments[i++], [Validators.required, Validators.minLength(8)]
                )
            );
        });
    }
    
    checkForError(post: any) {
        const inputForm = this.commentForm.get('comment' + post.post_id);
            if(inputForm.errors && (inputForm.dirty || inputForm.touched )) {
                return true;
            }
           return false;
        }
    }