Tek*_*Tek 2 javascript ng-class angular
我正在使用 Angular 2.0 beta 15。
最初我在开发应用程序时遇到了这个问题。然后我决定尝试用最简单的情况来重现它。请参阅下面的代码
//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngClass]="{'red-heading':isAlertOn, 'blue-heading':!isAlertOn}">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
isAlertOn:boolean;
constructor() {
this.name = 'Angular2';
this.isAlertOn = false;
}
(function(){
setTimeout(function(){
console.log("in here");
this.isAlertOn = true;
},2000);
})();
}
Run Code Online (Sandbox Code Playgroud)
由于我在应用程序中使用动画,因此我想延迟触发类更改。为了做到这一点,我使用 setTimeout。
我读过,一般来说,所有更改都是由 NgZone 手动处理的(我认为对于某些较旧的 alpha 版本)。现在这些更改应该自动处理。要么我遗漏了一些东西(在 Angular 2.0 中仍然是新的),要么可能有不同的方法。
提前谢谢你们了。
----------------------------------------------------------新更新 2016-04 -26 15:28--------------------------------------------------------
好吧,我刚刚弄清楚使用 CSS 动画的方法:
在CSS中这样做:
@keyframes blueToRed{
0% {color: blue}
100% {color:red;}
}
.blue-to-red-heading {
animation-name: blueToRed;
animation-duration: 2s;
/*animation-delay:2s; */ /*uncomment this for delays*/
animation-fill-mode: forwards;
}
Run Code Online (Sandbox Code Playgroud)
然后在app.ts中
//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngClass]="{'blue-to-red-heading':isAlertOn}">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
isAlertOn:boolean;
constructor() {
this.name = 'Angular2';
this.isAlertOn = true;
}
}
Run Code Online (Sandbox Code Playgroud)
--------------------------------------------------原答案------------------------------------------------ ------------- 我认为你问了一个很好的问题。
我无法弄清楚到底为什么,但问题出在立即函数上。
一旦你声明了你的函数,但没有在声明中立即运行它。有用。
是的,另一件事:setTimeout 似乎搞乱了“这个”......
我在 app.ts 上做了什么:
//our root app component
import {Component, OnInit} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngClass]="{'red-heading':isAlertOn, 'blue-heading':!isAlertOn}">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
isAlertOn:boolean;
constructor() {
this.name = 'Angular2';
this.isAlertOn = false;
this.setAlert();
}
ngOnInit() {
// this.setAlert(); //this works the same way
}
setAlert(){
let component = this;
setTimeout(function(){
console.log("in here");
component.isAlertOn = true;
},2000);
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1909 次 |
| 最近记录: |