angular - 在 Angular 中使用响应式(Reactive)形式触及并有效

标签 angular angular-reactive-forms

我如何在 Angular 4 中使用 react 形式来使用 touched 和 valid 属性。我在模板驱动形式中使用过,你可以把这个 <span class="text-muted" *ngIf="!fname.valid && fname.touched"> Please enter a valid first name</span>在输入字段下方。我还了解到响应式(Reactive)形式会更好,因为您必须在 component.ts 中编写逻辑。所以我希望它以 react 形式实现,并且我坚持如何使用 touched 和 valid 属性。

html

<form [formGroup]="form" (ngSubmit)="onSignIn(form)">
    <div class="form-group">
        <input type="text" class="form-control" id="email" placeholder="Enter email" formControlName="email">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="password" placeholder="Password" formControlName="password">
    </div><button class="btn btn-primary btn-block" type="submit" [disabled]="!form.valid">Sign In</button>
</form>

ts

 ngOnInit() {
    this.form = this.formBuilder.group({
      email: [null, [Validators.required, Validators.email]],
      password: [null, Validators.required],
    });
  }

  onSignIn(form: FormGroup){
    const email = form.value.email;
    const password = form.value.password;
    this.authService.loginUser(email, password)
    .subscribe(
      data => {
        this.router.navigate(['/settings']);
        alert("Login Successful");
        console.log(data);
      },
      error => {
        alert("Invalid Email or Password");
        console.log(error);
      });
  }

最佳答案

试试这个

<span class="text-muted" *ngIf="!form.controls['email'].valid && 
                 form.controls['email']?.touched"> Please enter a valid first name</span>

关于angular - 在 Angular 中使用响应式(Reactive)形式触及并有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46499786/

相关文章:

Angular 6 Jwt拦截器

javascript - 比较具有相同属性但混合在一起的两个对象不遵循字母规则

angular - 包含带有 Angular FormArray 的单选按钮的 FormGroup

javascript - Angular Material MatChipList - 如何在动态 FormArray 上使用它?

angular - Ubuntu 16.04 上的 NPM 安装错误,但 Windows 10 上没有

angular - 为什么没有 <app-root> 的其他组件不会出现在 index.html 上?

html - 当我按 Enter 时, Angular 形式的按钮为 "clicked"

angular - 如何测试一个简单的 Angular Reactive Form

angular - 如何使用 Angular5 检查表单控件的变化

typescript - 使用 Electron 时,我应该如何为 Angular 2 配置基本 href?