Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: How to access to form validation fields in Component.ts [duplicate]

For example I have a form ( not with FormGroup ) and view lookes like this

<form #f="ngForm" novalidate>
     <label>Email</label>
     <input type="email" [(ngModel)]="player.email" class="form-control" name="email" #email="ngModel" required>

     <!-- with #email code, now, in view, I have variable with name email!!! -->
</form>

With #email tag I declare a variable with name 'email' and with this variable I can check for validation errors. For example

 <div [hidden]="email.valid || email.pristine"
               class="alert alert-danger">
            email is required
 </div>

How can I access this variable in my component class?

like image 902
Grigor Aleksanyan Avatar asked Jan 22 '26 14:01

Grigor Aleksanyan


1 Answers

You have to use it by declaring ViewChild as below in your component :

export class MyCompoment {
  @ViewChild('email') email: ngModel;

  ngOnInit(){
    console.log(this.email);
  }
}
like image 51
ranakrunal9 Avatar answered Jan 25 '26 07:01

ranakrunal9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!