在 Angular 中使用反应式形式接触和有效 [英] touched and valid using reactive forms in Angular

查看:28
本文介绍了在 Angular 中使用反应式形式接触和有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用 angular 4 中的反应形式使用触摸和有效的属性.我在模板驱动的表单中使用过,你可以把这个 <span class="text-muted" *ngIf="!fname.valid && fname.touched">请在输入字段下方输入有效的名字.我还了解到响应式表单会更好,因为您必须在 component.ts 中编写逻辑.所以我希望它以反应形式实现,并且我被困在如何使用触摸和有效属性上.

How can i use the touched and valid properties using reactive forms in angular 4. I've used in template driven forms and you can just put this <span class="text-muted" *ngIf="!fname.valid && fname.touched"> Please enter a valid first name</span> below the input field. I've also learned that reactive forms would be better since you have to write the logic in the component.ts. So i want it to implement in the reactive form and i'm stuck on how to use the touched and valid properties.

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>

<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">登录</button></表单>

<块引用>

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 中使用反应式形式接触和有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆