【发布时间】:2017-02-06 21:16:52
【问题描述】:
如何获取*ngFor 中的类的快照以将时间/状态/人性化值保存在局部变量中?
例如,timer.remaining = timer.expires - Date.now()
<ion-card class="timer" *ngFor="let timer of timers">
<ion-card-content>
<ion-card-title>{{timer.humanize(timer.remaining) }}</ion-card-title>
<div class="card-subtitle">{{timer.label}}</div>
</ion-card-content>
<ion-note>remaining: {{timer.remaining/1000}}</ion-note>
<button ion-button block icon-left
[color]="lookup[timer.state].color"
(click)="timerClick(timer)"
>
<ion-icon [name]="lookup[timer.state].icon" ></ion-icon>
{{timer.label}}
</button>
</ion-card>
我想在ngFor 中调用一次timer.snapshot() 以获取所有显示属性。
解决方案:
谢谢,我用管道转换了Timers,然后将其推入*ngFor
// Pipe
@Pipe({name: 'toJSON', pure: false})
export class ToJsonPipe implements PipeTransform {
transform(value: any| Array<any>): any | Array<any> {
let unwrap = false;
if (!Array.isArray(value)) {
value = [value];
unwrap = true;
}
const result = value.map( (o)=>{
if (o && o.toJSON) return o.toJSON();
else return {};
})
return unwrap ? result[0] : result;
}
}
// html template
<ion-card class="timer" *ngFor="let timer of timers | toJSON ">
【问题讨论】:
-
最好的方法是创建管道,它会为你计算剩余时间。我认为,所有其他方法都是黑客攻击。