2016-03-10 66 views
4

我正在构建模型驱动的Angular2表单。我找到的大多数例子都会禁用提交按钮,直到表单有效。但是,我不是这种模式的粉丝,并且在提交表单后宁愿向用户显示任何可能的错误。表单提交后角度2显示验证错误

我在提交之后比较了我的表单ControlGroup数据之前&并且看不到任何区别。

enter image description here

有没有一种方法,以确定是否提交表单,这样我可以显示我在线验证错误?

回答

0

我不认为接受的答案 - 以及相关的更新角度确实解决了这个问题。

你可以使用form.submitted?标志来确定用户是否已经尝试提交 - 但不会自动显示错误(例如,如果您有必填字段并且用户在您的表单上没有输入任何内容,但只需点击提交,那么您会希望所有需要的字段显示所需的错误通知)。

onSubmit() { 
    if (this.form.valid) { 
     console.log('form submitted'); 
    } else { 
     this.validateAllFormFields(this.form); 
    }; 
    } 

    validateAllFormFields(formGroup: FormGroup) { 
    Object.keys(formGroup.controls).forEach(field => { 
     const control = formGroup.get(field);    
     if (control instanceof FormControl) {    
     control.markAsTouched({ onlySelf: true }); 
     } else if (control instanceof FormGroup) {  
     this.validateAllFormFields(control);   
     } 
    }); 
    } 

信贷和充分的解释here

这可以如下完成。