Component.ts
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SampleComponent extends SortableComponent implements OnInit {
public countNumbers: number = 0;
public sampleItems;
constructor(private sampleService: SampleService,) {
super();
}
ngOnInit() {
this.refreshList();
}
private refreshList() {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad + 1;
this.sampleService
.getSample()
.then(
(response: any) => {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad - 1;
this.sampleItems = response;
},
(reason: Error) => {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad - 1;
console.log(reason);
},
);
}
}模板
<div class="col-sm pt-4" *ngIf="numberOfAssetsLeftToLoad !== 0">
<loader loadingText="Loading Sample..." cssClass="w-50"></loader>
</div>
<div class="col-sm pt-4" *ngIf="numberOfAssetsLeftToLoad === 0">
<div *ngFor="let item of sampleItems;">{{item}}</div>
</div>问题是,在模板中使用OnPush策略值不会像ts文件那样适当地更改。例如,numberOfAssetsLeftToLoad停留1,加载不结束。
发布于 2022-08-29 09:26:06
您必须手动告诉角才能执行更改检测。只需注入ChangeDetectorRef并在更改属性的地方调用markForCheck():
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SampleComponent extends SortableComponent implements OnInit {
public countNumbers: number = 0;
public sampleItems;
constructor(private cd: ChangeDetectorRef, private sampleService: SampleService,) {
super();
}
ngOnInit() {
this.refreshList();
}
private refreshList() {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad + 1;
this.cd.markForCheck();
this.sampleService
.getSample()
.then(
(response: any) => {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad - 1;
this.sampleItems = response;
this.cd.markForCheck();
},
(reason: Error) => {
this.numberOfAssetsLeftToLoad = this.numberOfAssetsLeftToLoad - 1;
this.cd.markForCheck();
console.log(reason);
},
);
}
}https://stackoverflow.com/questions/73526668
复制相似问题