角度:模板在数组长度不变的情况下将数组放倒

时间:2018-12-10 22:52:58

标签: javascript angular typescript javascript-objects angular2-changedetection

这是父组件的模板:

<ng-container *ngFor="let set of timeSet; index as i">
    <time-shift-input *ngIf="enabled"
        [ngClass]="{ 
            'mini-times' : miniTimes, 
            'field field-last': !miniTimes,
            'field-central': !canAddSet,
            'field-central--long': (canAddSet || canDeleteSet) && !miniTimes }"
        [startHour]="set.startHour" 
        [endHour]="set.endHour"
        [endsNextDay]="set.endsNextDay" 
        [canAddSet]="canAddSet()"
        [canDeleteSet]="canDeleteSet(i)"
        [required]="true"
        (onAddSet)="onAddSet(i)"
        (onDeleteSet)="onDeleteSet(i)"
        (onChange)="onShiftTimes($event, i)"></time-shift-input>
</ng-container>

以下是触发timeSet事件后将更新onChange数组的代码:

public onShiftTimes( set: TimeSchedule | Array<TimeSchedule>, ind?: number ): void {
    if ( ind !== undefined ) {
        this.timeSet[ind] = <TimeSchedule>set;
    } else {
        this.timeSet = <Array<TimeSchedule>>set;
    }
    this.timeChanged.emit({
        data: this.timeSet,
        di: this.dayIndex
    });
}

每次调用<time-shift-input>方法时,子组件onShiftTimes都会重新呈现,即使数组的长度保持不变。

这真是令人讨厌,因为它以令人讨厌的方式破坏了用户体验(移开焦点等)。我认为推送或更新现有数组的索引不会更改该数组的对象引用,因此不会触发ngFor循环。但是,ngOnInit中的<time-shift-input>每次在onShiftTimes之后都会被调用...

任何想法如何防止重新渲染?

1 个答案:

答案 0 :(得分:1)

RTFM,正如他们所说。

trackByFn来解救-这是解决我的问题的简单而正确的解决方案。有关此宝石的更多信息:
https://angular.io/api/common/NgForOf#ngForTrackBy
https://www.concretepage.com/angular-2/angular-4-ngfor-example#trackBy