问题 在angular2中的表单提交上显示错误消息?


我已经实现了模型驱动的表单 这个演示。如果用户没有输入任何内容并提交表单,我将使用此逻辑显示错误消息

<div *ngIf="(!myForm.find('sku').valid && submitted)">**sku is required</div>

我传递一个布尔变量'submitted'来检查控件在提交时是否有效。有没有办法检查控件的状态而不手动传递变量? Angular2表单为我们提供了6个类 ng-touchedng-untouchedng-validng-invalidng-pristine,和 ng-dirty。我想仅使用这些类来显示错误消息。


7389
2018-02-03 05:36


起源

CSS是一个标记,不能用于逻辑。您可以编写JS或TS来检查元素上是否存在这些类,但是当角形式控件已经为您执行此操作时,这将重新发明轮子。 - SnareChops
@SnareChops在angularjs中有一个像form一样的控件。$ submitted ...在angular2中有类似的东西吗? - abhilash reddy
在angular2中,如果表单无效,则永远不会“提交”。因此表单永远不会具有“已提交”状态。有一个很棒的指南 这里 这非常深入到角形。我建议从上到下阅读整个页面。它将解释如何做你提出的一切。 - SnareChops
谢谢你我会读到它... - abhilash reddy
@dfsq是的,我一直在做手动,但想知道是否有角度的任何规定 - abhilash reddy


答案:


我知道这个问题是很久以前发布的,但我遇到了同样的问题,我想利用角度控制状态,所以发现这个工作正常:

首先,如果控件不是原始的,我会显示错误:

<span class="help-block" 
      *ngIf="request.get('control').hasError('required') && 
            !request.get('control').pristine">
      This field is required!
</span>

然后你可以通过所有控件并在onSubmit函数中将它们标记为脏:

onSubmit() {
//validations
this.form.updateValueAndValidity();
if (this.form.invalid) {
  Object.keys(this.form.controls).forEach(key => {
    this.form.get(key).markAsDirty();
  });
  return;
}

//call function for saving data
this.save(this.form.value);
}

希望这可以帮助


9
2018-05-09 16:41



if(this.form.invalid){Object.keys(this.form.controls).forEach(key => {this.form.get(key).markAsDirty(); this.form.updateValueAndValidity();});返回; } - Wang Xiao
我比手动设置标记更喜欢这个解决方案,因为在用户触摸表单控件之前显示错误消息会增加* ngIf的复杂性。 - The Muffin Man
惊人的技巧。这节省了大量时间,而且很简单。 - Pradeep


是...

你可以查一下 Angular form control's state 如此处所示。

角形控制的当前状态 

import {Component,View,bind} from 'angular2/core';
import {FORM_DIRECTIVES,CORE_DIRECTIVES,FormBuilder, Validators } from 'angular2/common';
import {bootstrap}        from 'angular2/platform/browser';


@Component({
  selector: 'my-app', 
  template: `
    <h1>LOGIN</h1>


        <form [ngFormModel]="loginForm"  #fm="ngForm"  (submit)="doLogin($event)">

        <input ngControl="name" type="text"  placeholder="Your name" #name="ngForm" required>

        <div [hidden]="name.valid || name.pristine" class="alert alert-danger">Name is required</div>

        <br/>

        <div>Valid ={{name.valid}}</div>
        <div>Pristine ={{name.pristine}}</div>
        <div>Touch ={{name.touched}}</div>

        <BR/><BR/>

        <input ngControl="password" type="password"  placeholder="Your password" #password="ngForm" required>

        <div [hidden]="password.valid || password.pristine" class="alert alert-danger">password is required</div>

        <br/>

        <div>Valid ={{password.valid}}</div>
        <div>Pristine ={{password.pristine}}</div>
        <div>Touch ={{password.touched}}</div>

        <BR/><BR/>

  <button type="submit" [disabled]="!loginForm.valid">Log in</button>

</form>
    `,
  directives: [ROUTER_DIRECTIVES,FORM_DIRECTIVES,CORE_DIRECTIVES]
})

export class Login { 
  constructor(fb: FormBuilder) {
    this.loginForm = fb.group({
      name: ["", Validators.required],
      password: ["", Validators.required]
    });
  }
  doLogin(event) {
    console.log(this.loginForm);
    event.preventDefault();
  }
 }

不要忘记单击登录按钮以在浏览器控制台中检查与表单关联的不同对象。而且我试图绑定 valid-invalid strip 到我以前实现的文本框中 Angular1。我希望这肯定会对你有所帮助。


2
2018-02-03 07:07



你已经禁用了按钮,直到表单有效...我希望按钮启用,即使表单无效,如果用户点击提交,那么我想显示错误消息 - abhilash reddy
原来如此 !然后看,有必要通过标志来检查用户是否按下了提交按钮。如果按下,则将flag设置为true,并将其与ngIf指令一起使用。你已经做到了。你还想要什么?你的样本也是正确的。 - micronyks
是的,我的代码工作正常...实际上有一个像$提交的标志angularjs ...想知道这样的规定是否在angular2也 - abhilash reddy
当您对文本框执行某些操作时,例如。触摸,使其变脏,在场景后面angular2使控件的状态发生变化,以便在即时效果UI上进行更改。所以你立即生效。但是如果你想用按钮的click事件做,那么你可以在TS / JS端访问表单控件的属性,通过一些手动工作,你可以做到。 - micronyks


我会利用 pristine 和/或 touched 特性:

  • 如果要在用户填写字段中的内容后显示错误,请使用 pristine 属性
  • 如果要在用户将焦点放在字段上后显示错误,请使用 touched 属性

这是一个示例:

<div *ngIf="(!myForm.controls.sku.valid && !myForm.controls.sku.pristine)">
  **sku is required
</div>

希望它能帮到你, 蒂埃里


0
2018-02-03 08:06





我需要在顶部显示一个验证横幅,显示提交时的所有表单验证错误,并且仅在提交时显示,这听起来像是您尝试做的事情。

目前运行ng2 ​​beta 17并且该框架不会阻止提交无效表单。浏览器将阻止提交所需的html验证,但任何其他自定义验证器都不会阻止表单提交。

我的方法最终是让验证摘要标题处理表单提交,并在成功时回调父级。如果表单无效,则横幅显示摘要并且不回调。

表单设置

<form (ngSubmit)="validationSummary.submit()" [ngFormModel]="myForm">
<div #validationSummary form-validation-summary [form]="myForm" [validSubmitCallback]="validSubmitCallback"></div>
...
<button type="submit" value="SaveButton" class="Button">Save</button>
</form>

页面与表单

export class SomeComponent implements OnInit {
    ...
    public validSubmitCallback: Function;
    ngOnInit() {
        this.validSubmitCallback = this.myFormSubmit.bind(this);
    }
    myFormSubmit() {
        alert("a valid form was submitted");
    }
}

验证摘要

@Component({
    selector: '[form-validation-summary]'
    ...

export class FormValidationSummary {
    @Input() public form: ControlGroup;
    @Input() public validSubmitCallback: Function; 
    ...
    submit() {
        if (this.form.valid) {
            this.validSubmitCallback();
        } else {
            this.formSubmitted = true;
       }
    }
}

与在表单上添加提交相关: https://github.com/angular/angular/issues/2960


0
2018-05-12 15:39





我创建了ng-message的angular 2版本。

语法与ng-message非常相似:

<form [formGroup]="formGroup">
    <label for="phoneNumber">Phone Number</label>
    <input type="text" id="phoneNumber" name="phoneNumber" formControlName="phoneNumber" required>
    <cl-ng-messages [control]="formGroup.get('phoneNumber')">
      <template clNgMessage="required">
         This is required
      </template>
      <template clNgMessage="pattern">
        the format of phone number is not correct
      </template>
    </cl-ng-messages>
</form>

https://github.com/changLiuUNSW/ng-messages2


0
2018-03-07 13:03