Handle Multiple Elements with Directives

Let’s learn about the `ViewChildren` decorator and how to use it with custom directives.

Sometimes, we need to invoke methods on their elements from the parent component’s context or just read data from child components. When we’re only working with a single component or element, it’s fairly easy. Usually, we implement this as follows:

  selector: 'app-form',
  template: `
	    <app-input #nameInput></app-input>
export class FormComponent {
	@ViewChild('nameInput') nameInput: InputComponent;

	// Here, we have an access to the InputComponent via this.nameInput

However, if we have multiple elements, we need to slightly change our approach to get access to all of them.

The ViewChildren decorator

Let’s consider that we have a simple component with a couple of div elements, and we want to access them from the component’s class. We can use something very similar to @ViewChild shown above called the @ViewChildren decorator. The @ViewChildren decorator gathers all elements that matches the selector, creating a list of elements.

This is another Angular core decorator that provides very similar outcomes. However, we should note that we might potentially select multiple elements so that the variable can no longer persist a single element.

Get hands-on with 1200+ tech skills courses.