如何使用 ngFor 绑定 angular 表单验证

How to bind angular form validation with ngFor

大家好,我正在尝试进行评论表单验证,对于每个 post 都有像 Facebook 这样的评论框,但我无法将评论表单与带有 formControlName="comment" 的 ngFor 索引绑定, 所以请任何人帮助我

我已经尝试了很多例子,但没有任何帮助。 我是下面的代码,请仔细检查并帮助我。


<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);
      }
    );
  }


通过使用上面的代码,当我触摸一个评论框时,我得到了对每个评论框的验证,但我只希望对我触摸的特定评论框进行一次验证。

每个输入需要不同的 formControlName。

您可以使用任何您想要的作为 formControlName 。

我用作formControlName ="comment" + 'the id of the post' -> comment1,comment2...

这是 stackblitz: https://stackblitz.com/edit/angular-uteyji

所以你在 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> 

组件将是这样的:

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;
    }
}