Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

touched and valid using reactive forms in Angular

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>

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);
      });
  }
like image 341
Joseph Avatar asked Sep 30 '17 05:09

Joseph


People also ask

How do you validate a Reactive form?

In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.

What is difference between touched and dirty in angular?

The difference between touched and dirty is that with touched the user doesn't need to actually change the value of the input control. touched is true of the field has been touched by the user, otherwise it's false. The opposite of touched is the property untouched .

What is Ng touched in angular?

CSS Classes ng-untouched The field has not been touched yet. ng-touched The field has been touched. ng-pristine The field has not been modified yet. ng-dirty The field has been modified.


1 Answers

Try this

<span class="text-muted" *ngIf="!form.controls['email'].valid && 
                 form.controls['email']?.touched"> Please enter a valid first name</span>
like image 66
Arun Kumaresh Avatar answered Oct 15 '22 07:10

Arun Kumaresh