首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么属性值在模板onPush策略中不改变?

为什么属性值在模板onPush策略中不改变?
EN

Stack Overflow用户
提问于 2022-08-29 09:22:40
回答 1查看 36关注 0票数 0

Component.ts

代码语言:javascript
复制
@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);
        },
      );
  }
}

模板

代码语言:javascript
复制
<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,加载不结束。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-29 09:26:06

您必须手动告诉角才能执行更改检测。只需注入ChangeDetectorRef并在更改属性的地方调用markForCheck()

代码语言:javascript
复制
@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);
        },
      );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73526668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档