【问题标题】:*ngIf condition is not fired/doesn't update template in ngOnChanges*ngIf 条件未触发/不更新 ngOnChanges 中的模板
【发布时间】:2017-10-15 01:21:07
【问题描述】:

我有一个子组件不会触发*ngIf 的条件

子组件:

 export class child {
    @Input() user;
    @Input() list;

    listLength: number;
    showBtn: boolean = false;

 constructor(){}

 ngOnChanges(changes: SimpleChanges){

     this.userId = this.user.id;
     this.userList = this.list;
     this.listLength = this.userList.length;   // this updates everytime when changes happen on another component thats pushed from this component.

     if (this.listLength > 3){    // this doesn't fire until I refresh the page
        this.showBtn = true;
     }

【问题讨论】:

  • 你能记录listLength的值吗?

标签: angular ionic2 angular2-template ionic3


【解决方案1】:

您可能还会在浏览器控制台中收到错误输出。 如果您在 ngOnChanges() 中更新模型,则显式调用更改检测

  constructor(private cdRef:ChangeDetectorRef){}

  ngOnChanges(changes: SimpleChanges){

     this.userId = this.user.id;
     this.userList = this.list;
     this.listLength = this.userList.length;   // this updates everytime when changes happen on another component thats pushed from this component.

     if (this.listLength > 3){    // this doesn't fire until I refresh the page
        this.showBtn = true;
     }
     this.cdRef.detectChanges();
  }
}

【讨论】:

  • 我想您需要提供更多信息。理想情况下是允许重现问题的 Plunker。 Plunker 在New 按钮下提供了一个 Angular 模板。
【解决方案2】:

我用ngDoCheck() lifeCycle hook 解决了这个问题。

ngOnChanges(changes: SimpleChanges){
 this.userId = this.user.id;
 this.userList = this.list;
}

ngDoCheck(){
 if (this.list.length > 3){
        this.showBtn = true; 
    } else {
        this.showBtn = false;
    }
}

【讨论】:

    【解决方案3】:

    一个数组有一个静态指针。当您在 Angular2 中的数组中添加或删除元素时,数组指针保持不变,因此在您刷新浏览器之前视图不会更新。这是由于 angular2 变化检测系统。至少这是我的猜测。

    有人在这篇文章中写了一个关于Angular2变化检测的漂亮答案,也许它会对你有所帮助。

    angular 2 change detection and ChangeDetectionStrategy.OnPush

    【讨论】:

    • 谢谢兄弟,非常有用。
    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2016-08-12
    相关资源
    最近更新 更多