When I try to access the DOM of the document, I notice that the template is only partially executed. Using a setTimeout
helps me bypass the issue temporarily, but what is the correct way to handle this?
import { Component, Input, AfterContentInit } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'tabs',
templateUrl: './templates/app.html',
providers: [ AppService ]
})
export class ShowBookmarksComponent implements AfterContentInit {
private addListeners():void {
let timeoutId = setTimeout(() => {
let draggables = document.getElementsByClassName('session');
console.log(draggables);
console.log(draggables.length);
for (let i = 0; i < draggables.length; i++) {
console.log(i+' '+draggables.length)
}
clearTimeout(timeoutId);
}, 1000);
}
ngAfterContentInit() {
this.appService.getBookmarkLists(this.sessions)
.then(() => this.appService.getCurrentTabs(this.current_tabs))
.then(() => this.addListeners());
}
}
The appService
supplies the data used by the template to display the HTML content.
<section class="current_tabs">
<div class="session" *ngFor="let current_tab of get_keys(current_tabs);">
<div class="whatever"></div>
</div>
</section>
<section class="current_bookmarks">
<div class="session" *ngFor="let session of get_keys(sessions);">
<div class="whatever"></div>
</div>
</section>
Despite having both this.sessions
and this.current_tabs
correctly filled before calling addListeners
, the part corresponding to sessions
is rendered while the part of current_tabs
is not yet rendered.
This discrepancy can be observed when executing
console.log(document.documentElement.innerHTML)
before the setTimeout
.
<section class="current_tabs">
<!--template bindings={
"ng-reflect-ng-for-of": ""
}-->
</section>
<section class="current_bookmarks">
<!--template bindings={
"ng-reflect-ng-for-of": "my_session_201 etc etc etc (correctly filled)"
(Within the setTimeout, both sections are correctly filled.)
The goal in the code is to correctly retrieve
let draggables = document.getElementsByClassName('session');
, specifically those defined within <section class="current_tabs">
which may not be filled yet.
EDIT: Further details on Iterating over TypeScript Dictionary in Angular 2
get_keys(obj : any) : Object {
return Object.keys(obj);
}