Angular:列表数据修改后如何刷新视图



我有一个包含以下片段的视图:

<div *ngIf="step" [sortablejs]="orderedId" [sortablejsOptions]="optionsSortable">
<div *ngFor="let item of step.items" class="item">
<div class="position">{{item.position}}</div>
<div class="text">{{item.text}}</div>
</div>
</div>

在控制器中,我有以下片段:

export class AppComponent implements AfterViewInit {
step: StepInterface;
stepId: number;
orderedId: Array<number>;
constructor(private api: ApiService) {
this.stepId = 1 //Debug
this.optionsSortable = {
onUpdate: (event: any) => {
this.api.organize(this.stepId, this.orderedId).subscribe((response) => {
this.step = response;
this.buildArray();
});
}
};
}
ngAfterViewInit() {
this.api.get(this.stepId).subscribe((data) => {
this.step = data;
this.buildArray();
});
}
private buildArray() {
this.orderedId = [];
for (const item of this.step.items) {
this.orderedId.push(item.id);
console.log(clue.id);
}
}
}

事实上,我有可排序的div,当用户修改位置时,数据会用后端更新。问题是更新位置时,对象"步骤"被修改,{{item.position}}在视图中不会刷新。修改职位后,如何更新视图中的职位?

谢谢

ChangeDetectorRef

如果组件数据中的任何内容发生了更改,但没有反映视图,则可能需要通知Angular来检测这些更改(检测本地更改(并更新视图。

import { Component, Input, ChangeDetectionStrategy,ChangeDetectorRef } from 
'@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements AfterViewInit {
step: StepInterface;
stepId: number;
orderedId: Array<number>;
constructor(private api: ApiService,private cdr:ChangeDetectorRef) {
this.stepId = 1 //Debug
this.optionsSortable = {
onUpdate: (event: any) => {
this.api.organize(this.stepId, this.orderedId).subscribe((response) => {
this.step = response;
this.buildArray();
});
}
};
}
ngAfterViewInit() {
this.api.get(this.stepId).subscribe((data) => {
this.step = data;
this.buildArray();
});
}
private buildArray() {
this.orderedId = [];
for (const item of this.step.items) {
this.orderedId.push(item.id);
console.log(clue.id);
}
this.cd.detectChanges();
}
}

最新更新