Angular Templates

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:03:00

Assigns Values to Template Variables

Angular allows you to assign values to template variables, which are placeholders for data or elements in your template, making it easy to reference and manipulate them within the template.


<input #myInput (keyup)="inputValue = myInput.value" />
<p>{{ inputValue }}</p>

Variable Specifying a Name

You can define a variable with a specific name using the '#' symbol to reference elements or components in your template.


<div #myElement></div>
<p>{{ myElement.innerText }}</p>

Using NgForm with Template Variables

Template variables can be used with Angular's NgForm to access form controls and their values for validation and submission.


<form #myForm="ngForm">
  <input name="username" ngModel #username="ngModel" required />
  <p *ngIf="username.invalid">Username is required.</p>

Template Variable Scope

Template variables have a scope limited to the template in which they are defined, ensuring they don't interfere with variables in other parts of your application.


<div *ngIf="showElement">
  <p #localVariable>This is a local variable.</p>
<p>{{ localVariable }}</p> <!-- Error: localVariable is not defined here -->

Accessing in a Nested Template

You can access template variables in nested templates by referencing them at the appropriate level in your component's template structure.


<div *ngFor="let item of items">
  <div #myItem>{{ }}</div>
  <button (click)="displayItem(myItem.innerText)">Display Item</button>

Template Input Variable

Template input variables allow you to pass data into a template and use it for rendering or logic.


<ng-container *ngFor="let item of items; let i = index">
  <div #myItem>{{ }}</div>
  <button (click)="displayItem(myItem.innerText)">Display Item {{ i + 1 }}</button>
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
Accept cookies & close this