Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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.

like image 740
born2net Avatar asked Feb 17 '16 17:02

born2net


1 Answers

<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

  • What's the difference between @ViewChild and @ContentChild?
  • angular 2 / typescript : get hold of an element in the template
like image 150
Günter Zöchbauer Avatar answered Sep 18 '22 21:09

Günter Zöchbauer