Handle Multiple Elements with Directives
Let’s learn about the `ViewChildren` decorator and how to use it with custom directives.
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.
The ViewChildren
decorator
Let’s consider that we have a simple component with a couple of div
...