gpt4 book ai didi

angular - 如何将 Angular 表单验证与 ngFor 绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 23:46:16 25 4
gpt4 key购买 nike

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

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


<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...

这里是堆栈 Blitz : 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;
}
}

关于angular - 如何将 Angular 表单验证与 ngFor 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55946823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com