代码之家  ›  专栏  ›  技术社区  ›  BitfulByte

如何在表单上动态设置“已验证”类,以在提交后显示角度为5的验证反馈消息

  •  0
  • BitfulByte  · 技术社区  · 6 年前

    我使用的是基于模板的角度表单。我还使用了引导(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 必须存在于表单元素上才能用类显示DIV invalid-feedback . 我用这个: https://getbootstrap.com/docs/4.0/components/forms/#validation

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   BitfulByte    6 年前

    有了@chellapan v的回答,我能够构建我想要的解决方案。

    我已申请以下变更:

    第一次添加 #form="ngForm" 模板中的表单标记。其次,我更改了ngclass表达式以引用表单的提交状态,而不是引用在提交表单时手动设置为true的布尔值。最后,但并非最不重要的是,我在“保存”按钮的“提交”方法中传递表单。

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

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

    Submit方法现在采用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() {
        this.form.resetForm();
        this.category = {} as NewCategoryDto;
    }