如何将加载设置为错误输入为空

时间:2019-02-11 12:47:37

标签: angular

如果用户未输入任何值并且执行了必填字段的验证程序,那么我尝试将表单提交时的loading设置为false,以便在填写字段时加载程序消失。在onSubmit内部,我尝试了此操作,但是它不起作用。

if(!this.loginForm.controls.email.value || !this.loginForm.controls.password.value) {
    console.log("empty");
    this.loading=false;
  }

它甚至不会在控制台上打印为空

<form method="get" [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div *ngIf="loading" class="loader-container">
            <div class="loader"></div>
        </div>
<div *ngIf="(loginError && loginForm.controls.email.touched) && (loginForm.controls.password.touched) " class="login-error">
   <span>Email or Password incorrect</span>
</div>
<input type="text" formControlName="email" name="email" (focus)="focusEmailInput()" placeholder="email *"/>
<input type="text" formControlName="password" (focus)="focusPasswordInput()" placeholder="Password *"/>
<button type="submit">Send</button>
</form>

ts文件

export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  submitted = false;
  loading: boolean;

  constructor(private formBuilder: FormBuilder, private auth: AuthService, private route: Router) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    })
  }

 onSubmit() {
    this.loading = true;
    this.submitted = true;
    if (this.loginForm.invalid) {
      return;
  }

  if(!this.loginForm.controls.email.value) {
    console.log("empty");
    this.loading=false;
  }

1 个答案:

答案 0 :(得分:0)

您正在onSubmit()函数中检查条件无效的表单。由于表单无效,因此以下代码将不会执行。因此,请检查按钮本身中的无效条件。

如下所示检查发送按钮的条件

<button type="submit" [disabled]="loginForm.invalid" (click)="onSubmit()">Send</button>

     onSubmit() {
            this.loading = true;
            this.submitted = true;

          if(!this.loginForm.controls.email.value) {
            console.log("empty");
            this.loading=false;
}
    }