Angular2,模板仅在使用ngAfterContentInit或ngAfterViewInit函数时被部分执行

时间:2017-01-17 11:22:17

标签: angular typescript lifecycle domcontentloaded

当尝试访问文档的DOM时,我发现模板只是部分执行。如果我使用setTimeout我可以解决问题,但是如何正确地做到这一点?

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());
    }

 }

appService提供模板用于显示html的数据。模板:

<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>

不知何故*,与sessions对应的部分已填充,但current_tabs的部分未填充 。在调用this.sessions

之前,this.current_tabsaddListeners都已正确填充

*在console.log(document.documentElement.innerHTML)

之前执行的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)

(在setTimeout中执行时,两者都正确填充)

在代码中,我想要的是正确检索let draggables = document.getElementsByClassName('session');,但我没有得到<section class="current_tabs">中定义的那些,因为它尚未填充

编辑:更多核心Iterate over TypeScript Dictionary in Angular 2

get_keys(obj : any) : Object {
    return Object.keys(obj);
}

3 个答案:

答案 0 :(得分:1)

您需要等到设置current_tabs,然后显式调用更改检测(detectChanges()),然后才能直接添加侦听器:

constructor(private cdRef:ChangeDetectorRef){}

ngOnInit() {
    this.appService.getBookmarkLists(this.sessions)
    .then(() => this.appService.getCurrentTabs(this.current_tabs))
    .then(() => {
      this.cdRef.detectChanges();
      this.addListeners();
    });
}

答案 1 :(得分:0)

当新数据可用时(绑定,ajax请求等),通过角度非常频繁地调用AfterViewChecked来更新页面状态。您应该尝试将代码放在AfterContentInit中,当所有外部数据都加载到页面时调用它。

请参阅https://angular.io/docs/ts/latest/api/core/index/AfterContentInit-class.html

答案 2 :(得分:0)

由@GünterZöchbauer在Angular2, HostListener, how can I target an element? can I target based on class?解决。问题在于两个函数之间的

    .then(() => this.appService.getCurrentTabs(this.current_tabs))
    .then(() => this.addListeners());

渲染器需要显示视图。所以我应该在视图更新时调用addListeners。完成

    .then(() => {
        this.cdr.detectChanges();
        this.addListeners();
     });