我正在使用登录表单,如果用户输入无效的凭据,我们希望将电子邮件和密码字段都标记为无效,并显示一条消息,指出登录失败。如何从可观察的回调中将这些字段设置为无效?
模板:
<form #loginForm="ngForm" (ngSubmit)="login(loginForm)" id="loginForm">
<div class="login-content" fxLayout="column" fxLayoutAlign="start stretch">
<md-input-container>
<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email">
</md-input-container>
<md-input-container>
<input mdInput placeholder="Password" type="password" name="password" required [(ngModel)]="password">
</md-input-container>
<p class='error' *ngIf='loginFailed'>The email address or password is invalid.</p>
<div class="extra-options" fxLayout="row" fxLayoutAlign="space-between center">
<md-checkbox class="remember-me">Remember Me</md-checkbox>
<a class="forgot-password" routerLink='/forgot-password'>Forgot Password?</a>
</div>
<button class="login-button" md-raised-button [disabled]="!loginForm.valid">SIGN IN</button>
<p class="note">Don't have an account?<br/> <a [routerLink]="['/register']">Click here to create one</a></p>
</div>
</form>
登录方式:
@ViewChild('loginForm') loginForm: HTMLFormElement;
private login(formData: any): void {
this.authService.login(formData).subscribe(res => {
alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
}, error => {
this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
this.loginForm.controls.email.invalid = true;
this.loginForm.controls.password.invalid = true;
});
}
除了将输入无效标志设置为true之外,我还尝试将email.valid
标志设置为false,并将其也设置loginForm.invalid
为true。这些都不会导致输入显示其无效状态。
后端使用的端口是否不同于角度端口?如果是这样,这可能是CORS问题。您在后端使用什么框架。
—
Mike3355 '17
您可以使用
—
developer033
setErros
方法。提示:您应该在组件文件上添加所需的验证器。还有没有特定的原因将ngModel与反应形式一起使用?
@ developer033在这里参加聚会有点晚,但是那些看起来不像是反应式表单,而是模板驱动的表单。
—
thenetimp