2

How do i get the value of an html input element in my component class?

For example, i want to get the username from this input element in my component class.

<div class="row">
     <div class="input-field col s12">                  
          <input id="username" type="text" class="validate" name="username">
          <label for="username">Username</label>
    </div>
</div>

Then i need the value in my component class:

export class HomepageComponent {
     username = username;
}
3
  • angular.io/docs/ts/latest/guide/template-syntax.html How about using ngModel? :) Commented Apr 23, 2017 at 14:21
  • Yes, i have been researching about ngModel, but i couldn't wrap my head around the appropriate binding to use. @ajt-82 Commented Apr 23, 2017 at 14:23
  • I'd suggest you actually take a look at the tutorial. You got an answer, yes, but if you look at the tutorial you'd get the hang of the basics. Start here: angular.io/docs/ts/latest/tutorial/toh-pt1.html :) Commented Apr 23, 2017 at 14:28

1 Answer 1

4

You could use ngModel directive there (two way binding) or template variable which will help you to hold DOM.

<input id="username" type="text" class="validate" [(ngModel)]="userName" name="username">

OR

<input #usernameInput type="text" class="validate" 
   name="username" (input)="username = usernameInput.value">
Sign up to request clarification or add additional context in comments.

2 Comments

so i did this earlier but my problem is how to access that variable in the component class.
You could use this.username in component class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.