1
I’m using Angular 7.
My goal is to create a Directive to control the focus of some elements with the arrow keys (in this example, a side menu).
Let’s assume I have the following html:
<ul list>
<li>
<a #item routerLink="home">Home</a>
</li>
<li>
<a #item routerLink="about">Sobre</a>
</li>
</ul>
I created a Directive in Angular with the name Listdirective, and it is already declared in Appmodule.
In this Directive, I would like to receive all the elements that have the attribute #item
. I imagine I can do that with the @ViewChildren('item')
, but he’s returning me undefined
.
Follows code:
import { AfterViewInit, Directive, QueryList, ViewChildren } from "@angular/core";
@Directive({
selector: '[list]'
})
export class ListDirective implements AfterViewInit {
@ViewChildren('item') items: QueryList<any>;
ngAfterViewInit() {
console.log(this.items); // undefined
}
}
When I try to do this using a component instead of a Directive, it works perfectly.
This example I gave is a little different than what I’m trying to do (although I’ve tried it that way). I think the ideal is for me to have two Directives: the List (which would be in the ul tag) and the Listitem (which would be in the links), because that way I could better manipulate the events of the links.
Using the @ViewChildren(ListItem) items: QueryList<ListItem>
also did not work, returning me Undefined. It seems that the problem is really the fact that I’m trying this on a Directive, but I haven’t found anywhere the information that it’s impossible to do this with Directives.
EDITION
To continue my project, I solved the problem by using a component instead of a Directive, since the latter was not accepting Viewchildren.
I created a class that does the work, and whenever a component has a list of the type, just inherit from that class.
I would still like to do only with Directives, only moving to html, so the question remains:
Viewchildren can be used in a Directive?
Thank you for sharing your solution
– Jean Carlo