Angular2得到给定#id的Div位置

时间:2016-07-02 16:04:00

标签: angular angular2-directives

我正在Angular2中构建一个TimeLine时间表,方法如下:

        <div class="timelineRow" *ngFor="let team of teams">
            <div class="RowDescriptionColumn">{{team.title}}</div>
            <div class="scheduleblock" *ngFor="let date of dates; let index=index; let odd=odd; let even=even;">
                <div class="timeslot1" [ngClass]="{ odd: odd, even: even }" [attr.id]="team.teamId +'_'+ date.id +'_ts1'"></div>
                <div class="timeslot2" [ngClass]="{ odd: odd, even: even }" [attr.id]="team.teamId +'_'+ date.id +'_ts2'"></div>
                <div class="timeslot3" [ngClass]="{ odd: odd, even: even }" [attr.id]="team.teamId +'_'+ date.id +'_ts3'"></div>
                <div class="timeslot4" [ngClass]="{ odd: odd, even: even }" [attr.id]="team.teamId +'_'+ date.id +'_ts4'"></div>
            </div>
            <div class="eventBlock" *ngFor="let event of events" [style.left]="getPosition(team, event)">{{event.title}}</div>
        </div>

所以首先我建立时间段(每个日期4个)然后,在这些Timslot-Divs之上,我想要举办活动。事件必须从正确的日期开始,所以我尝试通过做一个jQuery(我知道:邪恶)来获得位置..

getPosition(team, event): string {
    if (this.dates) {
      let left = "0px";
      let found = this.dates.filter(myObj => new Date(myObj.date).toDateString() === new Date(event.start).toDateString())[0];
      if (found) {
        let pos = jQuery(this.elementRef.nativeElement).find('#' + team.teamId + '_' + found.id + '_' + 'ts3').position();
        console.log(pos);
        if (pos) {
          left = pos.left + "px";
        }
      }
      return left;
    }
  }

这不起作用,但我无法弄清楚如何获得&#34; underlaying&#34;的起始位置。时隙-DIV ..

P上。

1 个答案:

答案 0 :(得分:0)

我怀疑getPostion过早被调用。您可以让视图创建组件,然后使用ViewChildren / ViewChild在ngAfterViewChecked中重新定位。 见Viewchildren usage ngAfterViewChecked被多次调用,因此请确保不再调用您的重新定位逻辑