*ngIf 条件不是 fired/doesn 在 ngOnChanges 中不更新模板
*ngIf condition is not fired/doesn't update template in ngOnChanges
我有一个子组件不会触发 *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()
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;
}
}
数组有一个静态指针。当您在 Angular2 的数组中添加或删除元素时,数组指针保持不变,因此视图不会更新,直到您刷新浏览器。这是由于 angular2 变化检测系统。至少这是我的猜测。
有人在这篇文章中写了一个关于 Angular2 变化检测的漂亮答案,也许会对你有所帮助。
我有一个子组件不会触发 *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()
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;
}
}
数组有一个静态指针。当您在 Angular2 的数组中添加或删除元素时,数组指针保持不变,因此视图不会更新,直到您刷新浏览器。这是由于 angular2 变化检测系统。至少这是我的猜测。
有人在这篇文章中写了一个关于 Angular2 变化检测的漂亮答案,也许会对你有所帮助。