Tob*_*nke 25 javascript angularjs ngfor angular
在Angular 1中,我编写了一个自定义指令("repeater-ready"),用于ng-repeat在迭代完成时调用回调方法:
if ($scope.$last === true)
{
$timeout(() =>
{
$scope.$parent.$parent.$eval(someCallbackMethod);
});
}
Run Code Online (Sandbox Code Playgroud)
标记中的用法:
<li ng-repeat="item in vm.Items track by item.Identifier"
repeater-ready="vm.CallThisWhenNgRepeatHasFinished()">
Run Code Online (Sandbox Code Playgroud)
如何ngFor在Angular 2中实现类似的功能?
Abh*_*tap 30
您可以使用@ViewChildren来实现此目的
@Component({
selector: 'my-app',
template: `
<ul *ngIf="!isHidden">
<li #allTheseThings *ngFor="let i of items; let last = last">{{i}}</li>
</ul>
<br>
<button (click)="items.push('another')">Add Another</button>
<button (click)="isHidden = !isHidden">{{isHidden ? 'Show' : 'Hide'}}</button>
`,
})
export class App {
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@ViewChildren('allTheseThings') things: QueryList<any>;
ngAfterViewInit() {
this.things.changes.subscribe(t => {
this.ngForRendred();
})
}
ngForRendred() {
console.log('NgFor is Rendered');
}
}
Run Code Online (Sandbox Code Playgroud)
原始答案在这里 /sf/answers/2596184391/
Sas*_*sxa 15
你可以使用这样的东西(ngFor局部变量):
<li *ngFor="#item in Items; #last = last" [ready]="last ? false : true">
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用setter拦截输入属性更改
@Input()
set ready(isReady: boolean) {
if (isReady) someCallbackMethod();
}
Run Code Online (Sandbox Code Playgroud)
对我来说,使用Typescript在Angular2中工作.
<li *ngFor="let item in Items; let last = last">
...
<span *ngIf="last">{{ngForCallback()}}</span>
</li>
Run Code Online (Sandbox Code Playgroud)
然后你可以使用这个功能来处理
public ngForCallback() {
...
}
Run Code Online (Sandbox Code Playgroud)
解决方案非常简单。如果您需要知道何时ngFor完成将所有 DOM 元素打印到浏览器窗口,请执行以下操作:
为正在打印的内容添加占位符:
<div *ngIf="!contentPrinted">Rendering content...</div>
display: none为内容创建一个容器。打印所有项目后,执行display: block。contentPrinted是一个组件标志属性,默认为false:
<ul [class.visible]="contentPrinted">
...items
</ul>
添加onContentPrinted()到组件中,ngFor完成后自动禁用:
onContentPrinted() {
this.contentPrinted = true;
this.changeDetector.detectChanges();
}
并且不要忘记使用ChangeDetectorRef来避免ExpressionChangedAfterItHasBeenCheckedError。
last值last在 上声明变量ngFor。li当此项是最后一项时,在内部使用它来运行一个方法:
<li *ngFor="let item of items; let last = last">
...
<ng-container *ngIf="last && !contentPrinted">
{{ onContentPrinted() }}
</ng-container>
<li>
contentPrinted组件标志属性onContentPrinted() 只运行一次。ng-container不影响布局。| 归档时间: |
|
| 查看次数: |
27575 次 |
| 最近记录: |