DOM Element Template Variable
In this example, we’ll create a template variable called “ageField” for the input element. Then we’ll create a button element that will refer this template variable to display the message.
app.component.html
<h2>Are you Eligible for Voting?</h2>
<input #ageField type="number" name="age" id="age" placeholder="Enter the age"/>
<button type="button" (click)="checkAge(ageField.value)">Check</button>
<p>{{message}}</p>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
message: string = 'Waiting for result...';
checkAge(arg: string) {
const age: number = Number.parseInt(arg);
if (age >= 18) {
this.message = 'Yes, you can vote.';
} else {
this.message = 'No, you can not vote.';
}
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
Output:
Understanding Templates Variable in Angular
Template variables in Angular allow us to use the data from one part of the template to another part of the same template. There are various use cases where these template variables come in handy. For example, responding to the user input or responding to the form submission.
In this article, we’ll explore what are template variables and how to use them.
Table of Content
- What are Template Variables?
- Syntax for Declaring Template Variables
- Scope of Template Variables
- DOM Element Template Variable
- Using NgForm with template Variables
Contact Us