简体   繁体   English

如何使用 ngFor 绑定角度表单验证

[英]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大家好,我正在尝试进行评论表单验证,对于像 Facebook 这样的评论框的每个帖子,但我无法将评论表单与 ngFor 索引与 formControlName="comment" 绑定,所以请任何人帮助我

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.通过使用上面的代码,当我触摸一个评论框时,我正在对每个评论框进行验证,但我只想对我触摸的特定评论框进行一次验证。

You need a different formControlName for each input.每个输入都需要不同的 formControlName。

You can use whatever you want as formControlName .你可以使用任何你想要的作为 formControlName 。

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

Here is the stackblitz: https://stackblitz.com/edit/angular-uteyji这是堆栈闪电战: https ://stackblitz.com/edit/angular-uteyji

So you need something like this in html:所以你需要在 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;
    }
}

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

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