我有一个不触发条件的组件*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;
}
您可能还会在浏览器控制台中收到错误输出。如果在 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();
}
}
我用ngDoCheck()
生命周期钩子解决了这个问题。
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;
}
}
数组
有一个静态指针。在 Angular2 中的数组中添加或删除元素时,数组指针保持不变,因此在您刷新浏览器之前不会更新视图。这是由于 angular2 变化检测系统。至少这是我的猜测。
有人在这篇文章中写了一个关于 Angular2 变化检测的漂亮答案,也许它会帮助你。
角度 2 变化检测和变化检测策略.OnPush