这是ngFor
的源代码,这个方法是用Angular 差异标识的变化来调用的,它通知对象或数组中的变化.但如果你注意到代码,there is a 101 which run for each element and inside it we notice for new records, there is a if condition where we run 102, so each row is created one by one!
private _applyChanges(changes: IterableChanges<T>) {
const viewContainer = this._viewContainer;
changes.forEachOperation(
(item: IterableChangeRecord<T>, adjustedPreviousIndex: number|null,
currentIndex: number|null) => {
if (item.previousIndex == null) {
// NgForOf is never "null" or "undefined" here because the differ detected
// that a new item needs to be inserted from the iterable. This implies that
// there is an iterable value for "_ngForOf".
viewContainer.createEmbeddedView(
this._template, new NgForOfContext<T, U>(item.item, this._ngForOf!, -1, -1),
currentIndex === null ? undefined : currentIndex);
} else if (currentIndex == null) {
viewContainer.remove(
adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex);
} else if (adjustedPreviousIndex !== null) {
const view = viewContainer.get(adjustedPreviousIndex)!;
viewContainer.move(view, currentIndex);
applyViewChange(view as EmbeddedViewRef<NgForOfContext<T, U>>, item);
}
});
for (let i = 0, ilen = viewContainer.length; i < ilen; i++) {
const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(i);
const context = viewRef.context;
context.index = i;
context.count = ilen;
context.ngForOf = this._ngForOf!;
}
changes.forEachIdentityChange((record: any) => {
const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(record.currentIndex);
applyViewChange(viewRef, record);
});
}