Welcome folks today in this blog post we will be using the validating
the input field data using two way
data binding & getters and setters method using 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
app.component.html
1 2 |
<p>The entered name is: {{name}}</p> <input type="text" [(ngModel)]="validateName"> |
And now we need to define the validateName
function 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 24 25 |
import {Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "sharing data" name:any get validateName():string{ return this.name } set validateName(value:any){ this.name = value if(this.name == "Kane"){ alert("Name already taken") } } } |
As you can see we have the get
and the set
methods where we are returning the value of the name
variable and then inside the set
method we are passing the entered value
and then we are checking if the value is equal to kane
and then we are showing the alert statement as shown below