Search⌘ K

Handle Multiple Elements with Directives

Explore how to manage multiple elements in Angular components using the @ViewChildren decorator and QueryList. Learn to create a custom directive for checkbox inputs to encapsulate logic and improve code clarity, enabling you to count selected checkboxes with clean and efficient architectural practices.

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:

@Component({
  selector: 'app-form',
  template: `
		<form>
	    <app-input #nameInput></app-input>
		</form>
  `
})
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.

In order to do this, Angular provides a new ...