编辑(2017年5月4日):
经过大量研究后,我很清楚,目前这种情况并不适用于本地人。办法。见这里:https://github.com/angular/angular/issues/7113
原帖:
目前,以下代码允许我在用户点击提交按钮时显示验证错误,而不在输入字段中输入有效的电子邮件:
import {
Component
} from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
submitted = false;
public submitForm(form: any): void {
this.submitted = true;
console.log(form);
}
}

.invalid-message {
color: yellow;
}

<form id="loginForm" #loginForm="ngForm" (ngSubmit)="submitForm(loginForm.value)">
<div class="form-group">
<input type="email" class="form-control form-control-lg" #email="ngModel" name="email" ngModel required pattern="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" placeholder="email">
<ng-container *ngIf="this.submitted && email.errors">
<small [hidden]="!email.errors.required" class="invalid-message float-right">EMAIL REQUIRED</small>
<small [hidden]="!email.errors.pattern" class="invalid-message float-right">INCORRECT EMAIL FORMAT</small>
</ng-container>
</div>
<button type="submit" form="loginForm" class="btn btn-secondary btn-block btn-lg">LOGIN</button>
</form>
&#13;
我想要的是当用户再次在输入中输入任何内容时,验证错误消息会自动消失。例如,这是Airbnb行为,如果您尝试登录网络,则可以体验到这一点。
答案 0 :(得分:0)
查看Reactive Forms模块。
它非常适用于此类事物,它会公开focus
,dirty
,touched
以及各种其他有用的属性。
您应该将每个输入绑定到[formControl]
然后在你的组件中。您可以使用formBuilder构建每个控件。
constructor(fb : FormBuilder) {
this.form = fb.group({
'firstName' : ['', Validators.required],
'lastName' : ['', Validators.maxLength(2)]
})
请注意,form
此处为FormGroup,其中公开了get
方法,您可以使用该方法测试组中的每个项目。
每个项目都是FormControl
- 您可以从API中找到所有这些内容。
e.g:
hasError(n: string){
return this.form.get(n).hasError('required');
}
如果您不想在用户输入时显示错误消息,可以在!focus
*ngIf
<div *ngIf="form.get('firstName').valid && !form.get('firstName').focus">
Error Message
</div>
编辑:当涉及到ReactiveForms时,还有很多值得一提的地方 - 这里不胜枚举。但是你可以看看其中的一些资源:
答案 1 :(得分:0)
如果在错误容器的ngIf中添加一个条件,检查当前输入当前是否具有焦点呢?
喜欢将此添加到你的ngIf:
ngIf="... && !elementHasFocus()"
并定义控制器内的当前功能。
function elementHasFocus(){
// ensure you inject $element in your controller in order to access the current element which triggered the bind function
return $element[0] === document.activeElement;
}