我正在使用登錄表單,如果用戶輸入無效的憑據,我們要將電子郵件和密碼字段標記爲無效,並顯示一條消息,指出登錄失敗。我如何着手將這些字段設置爲可觀察回調無效?如何手動將角度表單字段設置爲無效?
模板:
<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;
});
}
除了無效標誌設置輸入真實的我已經試過了email.valid
標誌設置爲false,並設置loginForm.invalid
也是如此。這些都不會導致輸入顯示無效狀態。
你的後端是否在角度以外的端口?如果是這可能是一個CORS問題。你在後端使用什麼框架。 – Drew1208
您可以使用'setErros'方法。提示:您應該在組件文件中添加必需的驗證器。也有一個具體的原因使用ngModel反應形式? – developer033