* ngIf条件未触发/不更新ngOnChanges中的模板

时间:2017-05-16 05:44:10

标签: angular ionic2 angular2-template ionic3

我有一个孩子的组件不会触发*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;
     }

3 个答案:

答案 0 :(得分: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();
  }
}

答案 1 :(得分:1)

我用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;
    }
}

答案 2 :(得分:1)

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

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

angular 2 change detection and ChangeDetectionStrategy.OnPush