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.
We'll cover the following...
We'll cover the following...
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.