2

Im working with angular 2 (TS) and need some help:

     constructor(public element:ElementRef){}  
     ngOnInit(){
       this.DOMready()
     }  

     DOMready() {
       if (this.element) {
         let testPosition = this.element.nativeElement.getElementsByClassName("_mypost");
         console.log(testPosition);
         for (let i = 0; i < testPosition.length; i++) {
         console.log(testPosition[i]);
         }
     }else {
        setTimeout(this.DOMready, 100)
    }

My problem is:
1) I can't properly catch time when document loaded and was prepeared to work with it (this code is the best what i have and yes, i tryed angular2 lifecycle Hooks...)
2) console.log(testPosition) - give the list that i want (with length 10),
but if it change on console.log(testPosition[0]) it give undefined. And my console.log(testPosition[i]) print nothing.
Thx)

Buggy
  • 3,539
  • 1
  • 21
  • 38

1 Answers1

2

If you want to access the DOM you need to use

 ngAfterViewInit(){
   this.DOMready()
 }  

or for projected content

 ngAfterContentInit(){ // or ngAfterContentChecked
   this.DOMready()
 }  

There are better ways to access elements in your view.

See for example angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567