2017-06-12 72 views
1

我在3秒后更新组件的消息,但它不在模板中更新。我试着安装angular2-polyfills(有些人说是尝试),我试过Angular2模板不更新

constructor(private cd: ChangeDetectorRef) 
{ .... 
    this.cd.markForCheck(); 
    .... 
} 

,但似乎没有任何工作。下面是完整的组件:

import { Component, ViewEncapsulation, ChangeDetectorRef } from 
'@angular/core'; 

//Defines a standard component 
@Component({ 
    selector: 'app', 
    templateUrl: './App.component.html' 
}) 
export class AppComponent { 
message: String = "hello"; //Message im trying to update 

//Just to try ChangeDetectorRef... 
constructor(private cd: ChangeDetectorRef) 
{ 
    //Timer that sets the message to '"HELLOWITHOUTWORLD" after 3 seconds 
    window.setTimeout(function() { 
     this.message = "HELLOWITHOUTWORLD"; 
     console.log("changed it " + this.message); 
    }, 3000); 
    //I ALSO TRIED DOING "this.zone.run" but kept getting zone is undefined 
    //window.setTimeout(function() { this.zone.run(() => { this.message = "HELLOWITHOUTWORLD"; console.log("changed it"); }); }, 3000); 

    //Some sites said that this would update the template... 
    this.cd.markForCheck(); 
} 
} 

和HTML:

{{message}} 

回答

1

我发现了一个类似的问题在这里:Angular 2, how to use setTimeout?

尝试过了一个简单的plnkr解决的办法是改变function() { /* ... */ }到箭头功能() => { /* ... */ }。这些箭头函数将正确设置块的上下文。

您的问题是function()中的this是一个隔离的范围,而不是您所期望的那样。对于更改检测,与angularjs相比,angular2及以上版本非常直观:它不再适用于摘要循环,并且很少需要您的输入。

如果有JS之前的经验,你能想象() => {}作为

var _this = this; 
function() { 
    var this = _this; 
    /* code */ 
}