2016-04-20 104 views
1

我有一個包含一個表的組件,我在tBody內部的一行中調用ngFor,問題是我需要指向我要應用在要運行的表上加載ngFor的最後一個元素之後。在加載最後一個項目之後調用一個指令ngFor

這裏是我的組件

import {Component} from 'angular2/core'; 
import {InfScrollTableService} from './inf-scroll-table.service' 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import {InfScrollTableDirective} from './inf-scroll-table.directive' 
@Component({ 
    selector: 'my-app', 
    template: ` 
    <table class="scrollable" infScrollTable> 
    <thead> 
     <tr> 
     <th class="small-cell">Code</th> 
     <th>Label</th> 
     <th>Area</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr *ngFor="#country of countries; #last=last" *ngIf="last"> 
     <td class="small-cell">{{country.id}}</td> 
     <td><a href="#" >{{country.id}}</a></td> 
     <td>{{last}}</td> 
     </tr> 
    </tbody> 
    </table> 
`, 
providers: [InfScrollTableService, HTTP_PROVIDERS], 
directives: [InfScrollTableDirective] 
}) 

export class AppComponent { 
    public countries; 
    constructor(private _infScrollTableService: InfScrollTableService){ 
    this._infScrollTableService.getCountries() 
    .subscribe(
     data => { 
     console.log(data); 
     this.countries=data; 
     }); 
    } 
} 

我的指令:

import {Directive, ElementRef} from 'angular2/core' 

@Directive({ 
    selector: '[infScrollTable]', 
}) 

export class InfScrollTableDirective{ 
    private _elem:HTMLTableElement; 

    constructor(el: ElementRef) { this._elem = el.nativeElement; console.log(el)} 
    bord(last:boolean){ 
    if(!last){ 
     return 
    } 
    console.log(this._elem) 
    var th = this._elem.tHead.rows[this._elem.tHead.rows.length - 1].cells; 
    var td = this._elem.tBodies[0].rows[0].cells; 
    var tdLen = td.length - 1; 
    var j = 0; 
    for (; j < tdLen; j++) { 
     if (th[j].offsetWidth > td[j].offsetWidth) { 
     td[j].style.width = th[j].offsetWidth + 'px'; 
     th[j].style.width = th[j].offsetWidth + 'px'; 
     } else { 
     th[j].style.width = td[j].offsetWidth + 'px'; 
     td[j].style.width = td[j].offsetWidth + 'px'; 
     } 
    } 
    } 
} 

在這裏,我想這最後的製作,我在ngIf通過的「最後」的最有意義的多的東西一個函數,但當我登錄在控制檯上收到的價值它是undefined

角1我達到了我想要的使用

$scope.$on('LastElem', function(){...}) 
+0

引起重新渲染的數據更改如何?目前,即使只在中間插入或刪除,也會發生這種情況(我猜這將在未來進行優化)如果將某個項目附加到「國家/地區」,該怎麼辦? –

回答

2

一種方法是對所有行應用指令並通過last。其中last爲真,該指令實際上做了一些事情。

@Directive({selector: '[isLast]'}) 
export class LastDirective{ 
    @Input() isLast:boolean; 
    @Output() lastDone:EventEmitter<boolean> = new EventEmitter<boolean>(); 
    ngOnInit() { 
    if(this.isLast) { 
     this.lastDone.emit(true); 
    } 
    } 
} 
<tr *ngFor="let country of countries; let last=last" [isLast]="last" (lastDone)="doSomething()"> 

你還可以創建自定義ngFor提供額外的功能。

+0

無法綁定到'isLast',因爲它不是已知的本地屬性 –

+0

您需要爲此元素應用指令或組合元素,該元素具有'@Input()isLast;'以便爲[​​[isLast] =「最後」工作。這個wozld需要使用上述指令的'@Component()'decorater中的'directive:[LastDirective]'。 –

+0

已經有該指令導入幷包含在指令中:[] –