【发布时间】:2018-06-27 12:29:30
【问题描述】:
所以我制作了一个带有登录表单的小型 Angular 5 应用程序。我已将“电子邮件”和“密码”作为必填字段。如果我选择该字段并失去焦点,它会变成红色,表示有问题。如果我现在提交我的表单,无论如何它都会调用我的服务和 API,即使有必要的错误。
这是我的代码:
<div class="example-container">
<form (ngSubmit)="onSubmit($event)" #loginForm="ngForm" *ngIf="this.showForm; else loadingTemplate">
<div class="form-group">
<mat-form-field>
<input matInput placeholder="Email" name="email" [(ngModel)]="loginModel.email" required>
</mat-form-field>
<mat-form-field>
<input matInput type="password" placeholder="Password" name="password" [(ngModel)]="loginModel.password" required>
</mat-form-field>
<mat-checkbox name="rememberMe" [(ngModel)]="loginModel.rememberMe">
Remember Me
</mat-checkbox>
<button mat-raised-button color="accent" type="submit">Submit</button>
</div>
</form>
<ng-template #loadingTemplate>
<div class="container">
<p>Please wait while your credentials are being checked...</p>
<img src="../../assets/giphy.gif">
</div>
</ng-template>
</div>
这是我的 .ts 文件的一部分:
loginForm: FormGroup;
ngOnInit() {
this.loginForm = this.fb.group({
loginModel: this.loginModel
});
}
onSubmit(e: Event) {
e.preventDefault();
if (this.loginForm.valid) {
this.showForm = false;
// TODO check if correct login
this.loginService.postLoginData(this.loginModel)
.subscribe(
data => {
this.router.navigateByUrl('/table');
},
error => {
// alert('login failed');
this.showForm = true;
this.openSnackBar(`Login for email: ${this.loginModel.email} failed!`);
});
}
}
我的 loginForm.valid 总是返回 true。有人能看出可能是什么问题吗?
【问题讨论】:
-
你是如何初始化
this.loginForm的? -
嗨,我已将它添加到我的 .ts 文件的代码中
-
它有
@ViewChild装饰器吗?
标签: angular validation angular-forms