Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...