[英]Can't select component declared in a template for Angular 2 using @ViewChildren
I'm migrating a jQuery application to Angular 2 and one of the passages that didn't work is the following selector for setting a behavior of the menus. 我正在将jQuery应用程序迁移到Angular 2,并且其中不起作用的段落之一是用于设置菜单行为的以下选择器。
$("li.dropdown").on("mouseenter mouseleave", function () { ... });
My strategy was to refer to it using @ViewChildren
and set the behavior in ngOnInit
method or, if necessary, in the ngAfterContentInit
method. 我的策略是使用引用它
@ViewChildren
并设置行为ngOnInit
方法,或者,如果有必要,在ngAfterContentInit
方法。 However, it seems that when I hit the breakpoint and type this.comboxes
in the console, the list undefined
. 但是,当我点击断点并在控制台中键入
this.comboxes
时,列表似乎undefined
。 I've googled around but didn't really hit anything useful (might be my ignorance to be blamed, though). 我在Google周围搜索,但并没有真正找到任何有用的信息(不过,可能是我的无知应受到责备)。
How can I go about to set a mousy behavior to some of the elements in the template? 如何设置模板中某些元素的行为? I'm fully open to another approach if this one is flawed.
如果这种方法有缺陷,我完全可以接受。
import { Component, ViewChildren } from "@angular/core";
@Component({
selector: "navbar",
template: require("./navbar.html")
})
export class NavBar {
@ViewChildren("li.dropdown") comboxes;
constructor() { console.log("NavBar created"); }
ngOnInit() { console.log("OnInit"); debugger; }
ngAfterContentInit() { console.log("OnCompInit"); debugger; }
}
Selector used by @ViewChildren
is not the same as JQuery uses: @ViewChildren
使用的选择器与JQuery使用的选择器不同:
Specifies a CSS selector that identifies this directive within a template.
指定一个CSS选择器,用于在模板中标识此伪指令。 Supported selectors include element, [attribute], .class, and :not().
受支持的选择器包括元素,[属性] 、. class和:not()。
Does not support parent-child relationship selectors.
不支持父子关系选择器。
Also @ViewChildren
by default will find only components and directives with matching selectors. 默认情况下,
@ViewChildren
还将仅查找具有匹配选择器的组件和指令。 You need to pass template reference to @ViewChildren
to query for DOM: 您需要将模板引用传递给
@ViewChildren
来查询DOM:
<div #templateRef>test</div>
<component #templateRef></component>
@ViewChildren('templateRef', {read: ElementRef}) nodes:QueryList<ElementRef>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.