简体   繁体   中英

Angular2 DOMContentLoaded, Lifecycle Hook

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM