Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

angular - What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce

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()
    ...

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()
   ...

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<div #foo>
@ViewChild() foo;
ngAfterViewInit(){
  foo.nativeElement...
} 

or if transcluded

@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.

or

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

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

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...