Welcome folks today in this blog post we will be using the viewchild
decorator to get values of the form
input fields using elementref
in typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you will see the below directory
structure of the angular app as shown below
And now we need to go to app.component.html
file and copy paste the below html code here we will have the input
field where we will be assigning the ngModel
directive as shown below. And also we have assigned the references
to each of the input fields. And we are getting the input for the username
e
app.component.html
1 2 3 4 5 6 7 8 9 |
<p>The name is:{{name}}</p> <p>The email is: {{email}}</p> <p>The password is: {{password}}</p> <label for="name">Enter the name</label> <input type="text" [(ngModel)]="name" #nameref><br> <label for="email">Enter the email</label> <input type="email" [(ngModel)]="email" #emailref><br> <label for="password">Enter the password</label> <input type="password" [(ngModel)]="password" #passwordref> |
And now we need to copy paste the below code inside the app.component.ts
file as shown below
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import {AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewInit { title = "sharing data" name:any email:any password:any @ViewChild('nameref') nameref!: ElementRef; @ViewChild('emailref') emailref!: ElementRef; @ViewChild('passwordref') passwordref!: ElementRef; ngAfterViewInit(){ this.nameref.nativeElement.focus() } } |
As you can see in the above typescript
code we have three variables where we will be storing the name
email and password values. And then we are using the ViewChild()
decorator and inside it we are passing the references of the name
email and password fields. And here we are using the ElementRef
as well. And then we are using the ngAfterViewInit()
defining this method inside it we are focusing
the input field using the nativeElement()
method and the focus()
method.