avatarAndy Dłubak

Summary

The article provides an in-depth guide on using ViewChild and ViewChildren to dynamically access and manipulate DOM elements in Angular applications.

Abstract

The article serves as a comprehensive tutorial for Angular developers seeking to understand and utilize ViewChild and ViewChildren decorators for dynamic DOM manipulation. It begins by introducing ViewChild as a tool for directly accessing a single DOM element via a template reference variable, demonstrating its practical use with code examples. The discussion then scales up to handling dynamic lists with ViewChildren and QueryList, showcasing how to interact with multiple elements generated by ngFor. The author presents three methods for accessing specific elements within a QueryList: index-based, data-attribute, and direct DOM query, each illustrated with examples. The article concludes by emphasizing the importance of these Angular features for creating responsive and interactive applications, offering a personal note on their effectiveness, and encouraging readers to follow for more insights on front-end development.

Opinions

  • The author considers ViewChild and ViewChildren as invaluable tools for Angular developers, providing a high level of control over the DOM.
  • These tools are described as offering precision and efficiency in handling dynamic content, which is crucial for responsive and interactive Angular applications.
  • The author expresses that mastering ViewChild and ViewChildren is a vital skill for both novice and experienced Angular developers, suggesting that it can enhance the enjoyment and smoothness of the development process.
  • A personal note from the author conveys their positive experience with these tools and their impact on front-end development, while also inviting readers to engage further by following on Medium.

Unlocking Dynamic DOM Access with ViewChild and ViewChildren

Imagine you’re a sculptor with a block of marble. You have tools at your disposal to shape this block into a masterpiece. In the world of Angular development, ViewChild and ViewChildren are such tools, enabling you to manipulate your template's elements dynamically. This article is your guide to mastering these powerful Angular features.

Abstract

  • Exploring ViewChild: Understanding its basic usage with an illustrative example.
  • Leveraging ngFor with ViewChildren and QueryList: Delving into dynamic lists and accessing their elements.
  • Accessing Specific Elements in QueryList: Three approaches—Index-Based, Data-Attribute, and Direct DOM Query—with examples.

The Power of ViewChild

Picture this: You have a single element in your Angular template that you need to interact with directly. This is where ViewChild comes into play.

Template:

<div #myDiv>Some content here</div>

Component:

@ViewChild('myDiv') myDivElement: ElementRef;

ngAfterViewInit() {
  console.log(this.myDivElement.nativeElement.textContent);
}

ViewChild allows direct access to a DOM element, identified by a template reference variable (#myDiv). It's like having a direct line to a specific part of your template.

Dynamically Handling Lists with ViewChildren

Now, let’s scale up. Imagine you have a list of elements generated by ngFor, and you need to access these dynamically created elements. Enter ViewChildren and QueryList.

Template:

<div *ngFor="let item of items">
  <!-- Assign a template reference variable here -->
  <div #myElement>{{ item }}</div>
</div>

Component:

import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html'
})
export class MyComponent implements AfterViewInit {
  @ViewChildren('myElement') elements: QueryList<ElementRef>;

  ngAfterViewInit() {
    // Now you can access the elements
    this.elements.forEach((elementRef) => {
      console.log(elementRef.nativeElement);
    });
  }
}

ViewChildren provides a QueryList of elements, offering a way to interact with multiple elements created by ngFor. It’s like having a toolbox for every tool in your shed.

Accessing Specific Elements in QueryList

Index-Based Approach

Use the index to pinpoint an element. Ideal when the order is known.

Template:

<div *ngFor="let item of items; let i = index">
  <!-- Use the index in the template reference variable -->
  <div #myElement>{{ item }}</div>
</div>

Component:

import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  // ... component metadata ...
})
export class MyComponent implements AfterViewInit {
  @ViewChildren('myElement') elements: QueryList<ElementRef>;

  ngAfterViewInit() {
    // Access a specific element by index
    const specificElementRef = this.elements.toArray()[specificIndex];
    console.log(specificElementRef.nativeElement);
  }
}

Data-Attribute Approach

Assign a unique data attribute to each element. Perfect for when elements have unique identifiers.

Template:

<div *ngFor="let item of items; let i = index">
  <div #myElement data-id="{{i}}">{{ item }}</div>
</div>

Component:

import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  // ... component metadata ...
})
export class MyComponent implements AfterViewInit {
  @ViewChildren('myElement') elements: QueryList<ElementRef>;

  ngAfterViewInit() {
    const specificId = 'someId';
    const specificElementRef = this.elements.find(
      (el) => el.nativeElement.getAttribute('data-id') === specificId
    );
    if (specificElementRef) {
      console.log(specificElementRef.nativeElement);
    }
  }
}

Direct DOM Query

Directly query the DOM when you need a quick and straightforward approach.

Template:

<div *ngFor="let item of items; let i = index">
  <div #myElement data-id="{{i}}">{{ item }}</div>
</div>

Component:

import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  // ... component metadata ...
})
export class MyComponent implements AfterViewInit {
  @ViewChildren('myElement') elements: QueryList<ElementRef>;

  ngAfterViewInit() {
    const specificElement = document.querySelector('[data-id="specificId"]');
    console.log(specificElement);
  }
}

Recap

We’ve explored the intricacies of ViewChild and ViewChildren in Angular, understanding how they can be used to interact with dynamic elements in your applications.

Personal Notes

In my own experience, these tools have been invaluable for creating responsive and interactive Angular applications. They offer a level of control over the DOM that is both powerful and efficient.

Conclusion

Whether you’re a seasoned Angular developer or just starting out, mastering ViewChild and ViewChildren is a vital skill. They offer precision and efficiency in handling dynamic content, making your Angular journey smoother and more enjoyable.

PS.

I hope you enjoyed reading this article, and also hope it will help you level up your skills. If you want to hear some more thoughts about front-end stuff don’t forget to follow me on Medium.

Junior Frontend Developer
Angular
Ngfor In Angular
Front End Development
Recommended from ReadMedium