Solution: Handle Multiple Elements with Directives
Here’s the solution to the task on handling multiple elements with directives as well as the expected result and explanation.
We'll cover the following
The solution relies on these four major points:
- Using
NgFor
to display inputs. - Providing a directive that gathers
value
from the single input. - Using
ViewChildren
to access all inputs and get their values. - Getting the values.
Explanation
Using NgFor
is very straightforward:
<input type="text" *ngFor="let _ of array"/>
The directive to gather the value is very similar to the one from the previous lesson. We only have to change getter
to fetch the value
instead of the checked
property:
@Directive({
selector: 'input[appText][type="text"]'
})
export class TextDirective {
public get value(): string {
return this.elementRef.nativeElement.value;
}
constructor(private elementRef: ElementRef) {
}
}
We can use this as follows:
<input appText type="text" *ngFor="let _ of array"/>
Now, here’s the ViewChildren
assignment:
@ViewChildren(TextDirective) texts: QueryList<TextDirective>;
Finally, we get the values using a map
operator. However, we can use a forEach
as well:
save() {
// Map values using the TextDirective API
const texts = this.texts?.map(text => text.value);
console.log(texts);
}
Solution
Here’s the complete solution:
Get hands-on with 1400+ tech skills courses.