Angular 2 * ng如果没有更新HTML模板
发布时间:2020-12-17 17:22:23 所属栏目:安全 来源:网络整理
导读:为什么* ngIf没有更新模板?无论isVisible在2秒后变为false,都会显示标题hello. @Component({ selector: 'my-app',template: ` h1 *ngIf="isVisible == true"{{title}}/h1 `})export class AppComponent { title = 'Hello!'; isVisible = true; constructor(
为什么* ngIf没有更新模板?无论isVisible在2秒后变为false,都会显示标题hello.
@Component({ selector: 'my-app',template: ` <h1 *ngIf="isVisible == true">{{title}}</h1> ` }) export class AppComponent { title = 'Hello!'; isVisible = true; constructor() { setTimeout(function() { this.isVisible = false; console.log(this.isVisible); },2000); } } 解决方法
有这样的匿名功能
setTimeout(function() { this.isVisible = false; },2000); 执行上下文(this)指向全局对象(窗口),但是您希望它是AppComponent实例.在这种情况下,您最好使用保留词法范围的arrow function: constructor() { setTimeout(() => { this.isVisible = false; },2000); } 您可以使用其他方法,例如使用Function.prototype.bind绑定上下文和保存上下文引用,但在这种情况下,箭头函数是最方便的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |