Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now

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.

Example

<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.

Example

<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.

Example

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

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.

Example

<div *ngIf="showElement">
  <p #localVariable>This is a local variable.</p>
</div>
<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.

Example

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

Template Input Variable

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

Example

<ng-container *ngFor="let item of items; let i = index">
  <div #myItem>{{ item.name }}</div>
  <button (click)="displayItem(myItem.innerText)">Display Item {{ i + 1 }}</button>
</ng-container>
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.
CONTACT US
Accept cookies & close this