typescript Angular2 视图模型中的布尔值不会更新 *ngIf 模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36734140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
boolean value in Angular2 viewmodel does not update *ngIf template
提问by J King
I have a weird behavior I need some help with. This is an angular2 and typescript app.
我有一个奇怪的行为,我需要一些帮助。这是一个 angular2 和 typescript 应用程序。
I have a template that contains the following html which uses ngIf:
我有一个包含以下 html 的模板,它使用ngIf:
<div *ngIf="loading" class="row">
<div class="small-3 small-centered columns" >
<img src="/Images/loading_spinner.gif" />
</div>
</div>
I have a button that triggers a function to change the value of loading
我有一个按钮可以触发一个函数来改变加载的值
export class ShiftEditComponent implements OnInit {
loading: boolean = false;
setLoading(value: boolean): void {
if (this.loading !== value) {
this.loading = !this.loading;
}
}
}
Here is the weird thing. If i specify the value of the value parameter from somewhere else in the class, the template does not update. BUTif I strip out the logic and just assign loading to its opposite, then it works and the template updates and the ngIf shows and does not show accordingly.
这是奇怪的事情。如果我从类中的其他地方指定 value 参数的值,模板不会更新。但是,如果我去掉逻辑并将加载分配给它的对立面,那么它就可以工作并且模板会更新并且 ngIf 会显示并且不会相应地显示。
THIS WORKS:
这有效:
setLoading(): void {
this.loading = !this.loading;
}
QUESTION: Why does this work and ngIf updates when i just assign the opposite value, but if I try to specify the value through a parameter the ngIf template does not update(show or hide)
问题:当我只分配相反的值时,为什么这会起作用并且 ngIf 会更新,但是如果我尝试通过参数指定值,ngIf 模板不会更新(显示或隐藏)
采纳答案by basarat
If i specify the value of the value parameter from somewhere else in the class, the template does not update
如果我从类中的其他地方指定 value 参数的值,模板不会更新
A common symptom that you have the wrong this
in that handler
一个常见的症状是你this
在那个处理程序中出错了
Fix
使固定
Use an arrow function https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
使用箭头函数https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html