3

I have a child a component that does not fire the condition for *ngIf

child component:

 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;
     }
Yasir
  • 1,391
  • 2
  • 23
  • 44

3 Answers3

1

You probably also get an error output in the browsers console. Invoke change detection explicitly if you update the model in 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();
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I guess then you'll need to provide more information. Ideally a Plunker that allows to reproduce the problem. Plunker provides an Angular template under the `New` button. – Günter Zöchbauer May 16 '17 at 06:59
1

I solved the problem with 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;
    }
}
Yasir
  • 1,391
  • 2
  • 23
  • 44
1

An Array has a static pointer. When you add or remove elements from the Array in Angular2, the array pointer stays the same and thus the view doesnt get updated until you refresh your browser. This is due to the angular2 change detection system. Atleast this is my guess.

Someone wrote a beautiful answer about Angular2 change detection in this article, maybe it will help you.

angular 2 change detection and ChangeDetectionStrategy.OnPush

Community
  • 1
  • 1
Karl Johan Vallner
  • 3,980
  • 4
  • 35
  • 46