Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Template Reference Variables in Angular

Template reference variables in Angular provide a way to access DOM elements or Angular components within a template. They are defined using the # symbol and can be used to interact with the elements directly in your component's class. This tutorial covers the basics of using template reference variables.

What are Template Reference Variables?

Template reference variables allow you to reference a DOM element or an Angular component from within your template. They are created using the # symbol followed by a variable name.

Basic Usage

Here is a simple example of defining and using a template reference variable:

<input #myInput type="text">
<button (click)="logValue(myInput.value)">Log Value</button>

export class AppComponent {
  logValue(value: string) {
    console.log(value);
  }
}

Accessing DOM Elements

You can use template reference variables to access and manipulate DOM elements directly:

<input #myInput type="text">
<button (click)="focusInput()">Focus Input</button>

export class AppComponent {
  @ViewChild('myInput') inputElement: ElementRef;

  focusInput() {
    this.inputElement.nativeElement.focus();
  }
}

Accessing Angular Components

Template reference variables can also be used to access Angular components and their properties or methods:

<app-child #childComp></app-child>
<button (click)="callChildMethod()">Call Child Method</button>

export class AppComponent {
  @ViewChild('childComp') childComponent: ChildComponent;

  callChildMethod() {
    this.childComponent.someMethod();
  }
}

@Component({
  selector: 'app-child',
  template: '<p>Child Component</p>'
})
export class ChildComponent {
  someMethod() {
    console.log('Child method called!');
  }
}

Using ngTemplateOutlet

Template reference variables can be used with ngTemplateOutlet to dynamically insert templates:

<ng-template #templateRef>
  <p>This is a template content</p>
</ng-template>

<div *ngIf="showTemplate">
  <ng-container *ngTemplateOutlet="templateRef"></ng-container>
</div>

export class AppComponent {
  showTemplate = true;
}

Key Points

  • Template reference variables provide a way to access DOM elements or Angular components within a template.
  • They are defined using the # symbol followed by a variable name.
  • Template reference variables can be used to access and manipulate DOM elements directly.
  • They can also be used to access Angular components and call their methods or access their properties.
  • Template reference variables can be combined with ngTemplateOutlet to dynamically insert templates.

Conclusion

Template reference variables are a powerful feature in Angular that allow you to interact with DOM elements and Angular components within your templates. By understanding and using template reference variables effectively, you can create more dynamic and interactive Angular applications. Happy coding!