touched and valid using reactive forms in Angular

后端 未结 2 1023
故里飘歌
故里飘歌 2021-01-02 04:02

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

相关标签:
2条回答
  • You can use it in similar way. To get the FormControl use get method on FormGroup object and then hasError:

    // in your template form.get('email').hasError('required') && form.get('email').touched form.get('email').hasError('email') && form.get('email').touched form.get('password').hasError('required') && form.get('password').touched

    You can also create some nice methods/getters for that in your component.


    edit (full code)

    <form [formGroup]="form" (ngSubmit)="onSignIn(form)">
        <div class="form-group">
            <input type="text" class="form-control" id="email" placeholder="Enter email" formControlName="email">
          <span class="text-muted" *ngIf="form.get('email').hasError('required') && form.get('email').touched">Email is required</span>
        </div>
        <div class="form-group">
            <input type="password" class="form-control" id="password" placeholder="Password" formControlName="password">
             <span class="text-muted" *ngIf="form.get('password').hasError('required') && form.get('password').touched">Password is required</span>
        </div><button class="btn btn-primary btn-block" type="submit" [disabled]="!form.valid">Sign In</button>
    </form>

    0 讨论(0)
  • 2021-01-02 04:32

    Try this

     <span class="text-muted" *ngIf="!form.controls['email'].valid && form.controls['email']?.touched"> Please enter a valid first name</span>
    
    0 讨论(0)
提交回复
热议问题