如何在ngFor中创建局部变量

时间:2017-02-06 08:39:53

标签: angular ionic2

如何在*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>

我想在timer.snapshot()内只调用一次ngFor以获取所有显示属性。

解决方案:

谢谢,我使用管道转换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 "> 

1 个答案:

答案 0 :(得分:0)

您应该在组件类或服务中创建要与*ngFor一起使用的值数组,然后使用*ngFor绑定到该数组,而不是将逻辑放入*ngFor本身。 可能存在黑客但是它们通常在Angulars变化检测中效果不佳,并且可能会损害您的组件性能。