【问题标题】:Selecting template element and passing to jQuery in Angular 2 component在 Angular 2 组件中选择模板元素并传递给 jQuery
【发布时间】:2017-03-21 05:37:05
【问题描述】:

我正在尝试研究如何在 Angular 2 中使用 jQuery。我一直在尝试遵循下面提到 Angular 应该控制 DOM 并且我应该将元素传递给 jQuery 的示例。

https://stackoverflow.com/a/30662773/657477

我想我不明白@ViewChild() 的工作原理。

我的组件模板中有一个 div:

<div id="screenshot">
 // ... content here
</div>

所以我将 jQuery 声明为 any:

declare var $:any;

添加此属性:

@ViewChild('screenshot') el:ElementRef;

然后要测试一下,只需尝试在 ngAfterViewInit() 中调用 hide 即可:

ngAfterViewInit() {
    $(this.el.nativeElement).hide();
}

这会引发异常:

无法读取未定义的属性“nativeElement”

所以我的视图查询没有找到元素?我检查了@ViewChild 的文档,它似乎将嵌套组件作为参数。我想我肯定在这里做错了什么。

我希望能够在组件中使用 jQuery 进行各种工作,因此我需要能够使用选择器然后调用 jquery 方法。

我是否使用了错误的方法?我应该如何将元素传递给 jQuery?

【问题讨论】:

    标签: jquery angular typescript


    【解决方案1】:

    需要做一个小改动,如下图,

    <div #screenshot>          //replaced id="screenshot" by #screenshot
       // ... content here
    </div>
    
    @ViewChild('screenshot') el:ElementRef;
    

    【讨论】:

    • 谢谢。看起来它现在正在工作。 (倒计时结束后我会接受)
    • &lt;div #screenshot id="screenshot"&gt; 是必需的,否则 ID 不会输出为 html。
    • 拯救了我的一天 :)
    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2017-09-23
    • 2019-03-16
    • 2022-01-13
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多