缺少在angular2(2种差异方式)文档中访问本机元素的正确方法是什么 [英] What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce

查看:106
本文介绍了缺少在angular2(2种差异方式)文档中访问本机元素的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular2中访问本机元素的正确方法是什么(2种比较方式) 所以我看过使用以下代码的代码:

What's the proper way of accessing native element in angular2 (2 diff ways) so I have seen code that uses:

constructor(ele: ElementRef) {
    let myEl = ele.nativeElement;
    // do some work on myEl such as jQuery(myEl).hide()
    ...

以及通过BrowserDomAdapter使用本机dom的代码:

As well as code that uses native dom via BrowserDomAdapter:

constructor(viewContainer:ViewContainerRef) {
   let dom = new BrowserDomAdapter();
   let el = viewContainer.element.nativeElement; 
   let myEle = dom.getElementsByClassName(el, element)[0];
   // or jQuery(myEle).hide()
   ...

我想知道什么是Pro/Cons和正确"的做事方式. 不幸的是,文档似乎仍然稀缺.

I am wondering what's the Pro / Cons and "proper" way of doing things. Unfortunately, the docs seem scarce still.

我假设后者会通过该界面为WebWorkers提供支持,但这只是我的假设.

I am assuming the latter will give you WebWorkers support through the interface, but it is just my assumption.

推荐答案

<div #foo>

@ViewChild() foo;
ngAfterViewInit(){
  foo.nativeElement...
} 

或已被排除

@ContentChild() foo;
ngAfterContentInit(){
  foo.nativeElement...
} 

允许按模板变量或组件或指令类型选择元素. (使用类型,您将获得组件实例而不是元素实例.

Allow to pick elements by template variable or component or directive type. (with a type you'll get the component instance instead of the element though.

constructor(@ViewChildren('foo') elements) {...  
constructor(@ContentChildren('foo') elements) {...  

@ViewChild提供实时视图,以匹配具有更改订阅的元素.

@ViewChild provides a live view to matching elements with changes subscription.

另请参见

  • What's the difference between @ViewChild and @ContentChild?
  • angular 2 / typescript : get hold of an element in the template

这篇关于缺少在angular2(2种差异方式)文档中访问本机元素的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆