Angular2等待DOM元素加载

时间:2016-07-26 22:13:39

标签: javascript typescript angular

我有一个具有成员数组变量的Component。该数组使用* ngFor绑定到DOM。当我向数组添加新变量时,我的视图会相应地更改。 Array保存选项卡名称,最初设置为只有1个选项卡。当我刷新页面数组重新初始化时,这正是我所期待的。但是当我退出然后重新登录(路由器导航)时,我看到所有以前的标签。这对我来说很奇怪,因为如果我console.log(myTabs)数组只有1个元素(homeTab)。

更新:

html的

<div style="display: table-caption" id="notify-tabs">
    <ul class="nav nav-tabs" role="tablist" id="nav-bar">
        <li role="presentation" data-toggle="tab" id="homeTab" [class.active]="activeTab==='homeTab'"><a (click)="setValues('home')">Home</a>
        <li role="presentation" *ngFor="let tab of myTabs" data-toggle="tab" id={{tab}} [class.active]="activeTab===tab.toString()"><a (click)="setValues(tab)">{{tab}}</a>
    </ul>
</div>

.component.ts

@Component({

    selector: 'notify-homepage',
        templateUrl: 'app/home/home.component.html',
        styleUrls: ['styles/css/bootstrap.min.css', 'styles/home.css'],
        directives: [DynamicComponent, TileComponent, MapComponent, HeaderComponent, ConversationComponent, ROUTER_DIRECTIVES]
})
export class HomeComponent{
    public myTabs: number[] = [21442];
    public activeTab: string = 'homeTab';

    ngOnInit() {
    //Assume fully operating MapService here
    this.subscription = this.mapService.conversationId.subscribe(
        (id: number) => {
            this.myTabs.push(id);
            this.setValues(id);
            this.activeTab = id.toString();               
        })
    }
    ngOnDestroy() {
    this.subscription.unsubscribe();
    ...
}
}

map.service.ts

@Injectable()
export class MapService {
    private conversationIdSource = new ReplaySubject<number>();
    public conversationId = this.conversationIdSource.asObservable();

    ...

     showConversation(id: number) {
         this.conversationIdSource.next(id);
     }
}

3 个答案:

答案 0 :(得分:0)

检查生命周期挂钩

  1. OnChanges https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges
  2. DoCheck https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#docheck
  3. 它们有助于跟踪Inputlocal变量中的变化。

    OnChanges个变量

    Input

    ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
      for (let propName in changes) {
        let chng = changes[propName];
        let cur  = JSON.stringify(chng.currentValue);
        let prev = JSON.stringify(chng.previousValue);
        this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
      }
    }
    

    DoCheck用于所有事情:

    ngDoCheck() {
      if (this.hero.name !== this.oldHeroName) {
        this.changeDetected = true;
        this.changeLog.push(`DoCheck: Hero name changed to "${this.hero.name}" from "${this.oldHeroName}"`);
        this.oldHeroName = this.hero.name;
      }
    }
    

答案 1 :(得分:0)

@Andrei 的答案有效,但我认为有一个更好,更优雅的解决方案。

只需结合使用@ViewChild()和设置器即可。

例如:

// component.html

<ng-el ... #myElement>

// component.ts

@ViewChild('myElement') set(el) {
  if (el) {
    console.log('element loaded!');
  }
}

答案 2 :(得分:0)

试试这个:

while(!document.getElementById('print-section')) {
  await new Promise(resolve => setTimeout(resolve, 100));
}