在 Angular 2+ 中将元素添加到 ngFor 后,您如何 运行 一些代码?
How do you run some code after an element is added to ngFor in Angular 2+?
我的组件中有一个函数可以将一个元素添加到视图中由 *ngFor 显示的数组。
我希望通过 id 定位添加的元素,并在将其添加到数组后滚动到它。问题是此代码在元素添加到视图之前运行。
我如何在 Angular 2+ 中解决这个问题?
您可以使用执行通知的自定义指令:
@Directive({ selector: '[afterAdd]')
class MyDirective {
@Output() added:EventEmitter = new EventEmitter();
ngAfterContentInit() {
this.added.next(null);
}
}
并像这样使用它:
<div *ngFor="let item of items" afterAdd (added)="doSomething(item)">
这样,父组件上的 doSomething()
将被 *ngFor
添加的每个项目调用(也用于数组中所有项目的初始添加)
或者,您也可以确保该项目已添加到 DOM 赞
constructor(private cdRef:ChangeDetectorRef) {}
...
this.items.push(newItem);
this.cdRef.detectChanges(); // sync
// here the item was added to the DOM already
我的组件中有一个函数可以将一个元素添加到视图中由 *ngFor 显示的数组。
我希望通过 id 定位添加的元素,并在将其添加到数组后滚动到它。问题是此代码在元素添加到视图之前运行。
我如何在 Angular 2+ 中解决这个问题?
您可以使用执行通知的自定义指令:
@Directive({ selector: '[afterAdd]')
class MyDirective {
@Output() added:EventEmitter = new EventEmitter();
ngAfterContentInit() {
this.added.next(null);
}
}
并像这样使用它:
<div *ngFor="let item of items" afterAdd (added)="doSomething(item)">
这样,父组件上的 doSomething()
将被 *ngFor
添加的每个项目调用(也用于数组中所有项目的初始添加)
或者,您也可以确保该项目已添加到 DOM 赞
constructor(private cdRef:ChangeDetectorRef) {}
...
this.items.push(newItem);
this.cdRef.detectChanges(); // sync
// here the item was added to the DOM already