igo*_*udi 5 render angularjs angular
我有一个Angular2主组件,它包含许多子组件和一个独立的倒计时组件(在下面的代码中命名为"clock").倒计时组件每秒更改它的标签,这会导致主组件和所有其他组件(不必要地)重新渲染.我怎么能防止这种情况?这是我的倒计时组件的来源:
import {Component, Input} from 'angular2/core';
@Component({
selector: 'clock',
template: `
<span>
{{caption}}
</span>
`
})
export class ClockComponent {
public caption;
@Input('seconds') seconds :number = 0;
constructor() {
var self = this;
setInterval(function(){
self.seconds--;
self.caption = self.getCaption(self.seconds);
}, 1000);
this.caption = this.getCaption(this.seconds);
}
getCaption (seconds): string {
let h = Math.floor(seconds / (60*60));
let m = Math.floor((seconds - 60 * 60 * h) / 60);
let s = seconds % 60;
return ((h < 10) ? '0' : '') + h + ':'
+ ((m < 10) ? '0' : '') + m + ':'
+ ((s < 10) ? '0' : '') + s ;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以想象它和"my-app"中的其他人一起被嵌入; 就像是:
<clock [seconds]="1800"></clock>
<other-comps>...</other-comps>...
Run Code Online (Sandbox Code Playgroud)
编辑(每条评论):当我的意思是重新渲染时,会发生这种情况:我已经在各种渲染操作中向其他组件添加了console.log打印输出(导航和问题,请参见下图),例如,组件具有一个类绑定器,例如:[class.selected] ="isSelected"并且我已经将console.log()添加到isSelected()方法,因此每次倒计时(时钟)都可以发现它每隔一秒被调用一次刷新自己.我想倒计时更改标签(从例如30分钟开始倒计时),不会影响导航和问题组件并导致它们重新渲染.
编辑(2):
以下是这个问题:http ://plnkr.co/edit/PwBfUQXyZyTrqPaqrwRm?p=preview
启动控制台并观察六个"q-nav被选中?" 每秒出现一次(从qnav组件打印).
这就是 Angular 的更改检测,它会在每个事件上调用,setInterval调用回调就是这样一个事件。
您可以将更改检测切换为OnPush仅在更新时或显式调用更改检测时进行更改检测@Input(),例如通过调用方法ChangeDetectorRefs
import {Component, Input, OnInit, EventEmitter, Output, OnChanges, ChangeDetectionStrategy} from \'angular2/core\';\n@Component({\n selector: \'q-nav\',\n template: `\n <span *ngFor="#a of currAnswers; #i = index" class="aii-qn"\n [class.selected]="isSelected(i)"\n (click)="onSelect(i)">\n <span class="badge">{{ i+1 }}</span>\n \xc2\xa0 </span>\n `,\n styles: [`\n .aii-qn {\n color: #0000ff;\n cursor: pointer;\n font-size: 2rem;\n }\n .selected {\n border: black solid 2px;\n }\n\n `],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nRun Code Online (Sandbox Code Playgroud)\n有关更多详细信息,请参阅:
\n http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
| 归档时间: |
|
| 查看次数: |
2107 次 |
| 最近记录: |