gpt4 book ai didi

css - 如何在表单上动态设置 'was-validated' 类以在提交后显示带有 Angular 5 的验证反馈消息

转载 作者:行者123 更新时间:2023-11-28 01:26:22 25 4
gpt4 key购买 nike

我在 Angular 中使用基于模板的表单。我还使用 bootstrap (v4),我希望在提交表单时显示一些验证消息。

这是我的表格:

<form [ngClass]="{'was-validated': wasValidated}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" [(ngModel)]="category.name" #name="ngModel" required maxlength="100"/>
<div *ngIf="name.invalid" class="invalid-feedback">
<div *ngIf="name.errors.required">
Name is required.
</div>
</div>
</div>
<button type="submit" class="btn btn-success" (click)="save()">Save</button>
</form>

我的组件如下所示:

category: Category;

wasValidated: boolean = false;

ngOnInit() {
this.reset();
}

save() {
this.wasValidated = true;
this.categoriesService.createCategory(this.category).subscribe(
() => {
this.notificationService.add(notifications.category_saved, {name: this.category.name});
this.reset();
},
() => this.notificationService.add(notifications.save_category_failed)
);
}

reset() {
this.wasValidated = false;
this.category = {} as Category;
}

这行得通,但我觉得它过于复杂,更像是一种解决方法,而不是正确的方法。实现此目标的最佳方法是什么?

注意:类 was-validated 必须出现在表单元素上才能显示类 invalid-feedback 的 div。我正在使用这个:https://getbootstrap.com/docs/4.0/components/forms/#validation

注意 2:我目前还没有防止错误提交表单的机制。我也想知道一个很好的解决方案!

最佳答案

根据@Chellappan V 的回答,我能够构建我想要的解决方案。

我已应用以下更改:

首先在模板中的form标签中添加了#form="ngForm"。其次,我更改了 ngClass 表达式以引用表单的提交状态,而不是引用在提交表单时手动设置为 true 的 bool 值。最后但同样重要的是,我在保存按钮上的提交方法中传递了表单。

<form novalidate #form="ngForm" [ngClass]="{'was-validated': form.submitted}">
<!-- form controls -->
<button type="submit" class="btn btn-success" (click)="submit(form)">Save</button>
</form>

在组件中,我使用 @ViewChild 将模板变量注入(inject)到组件中。

@ViewChild("form")
private form: NgForm;

提交方法现在采用 NgForm 类型的表单参数,用于在向后端发送请求之前检查表单是否有效:

submit(form: NgForm) {
if (form.valid) {
this.categoriesService.createCategory(this.category).subscribe(
() => {
this.notificationService.add(notifications.category_saved, {name: this.category.name});
this.reset();
},
() => this.notificationService.add(notifications.save_category_failed)
);
} else {
this.notificationService.add(notifications.validation_errors);
}
}

最后,reset 方法重置表单和模型,以便重新输入以提交下一个实例:

reset() {
this.form.resetForm();
this.category = {} as NewCategoryDto;
}

关于css - 如何在表单上动态设置 'was-validated' 类以在提交后显示带有 Angular 5 的验证反馈消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223053/

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