首页 > 解决方案 > How to use Observable variable in *ngFor

问题描述

I am using rxjs in my nativescript-angular app. In my case, I realize a simple animation by setting StackLayout's top with an observable variable 'myTop$'. Following codes work well, and the "StackLayout" moves as expected :

<AbsoluteLayout width="100%" height="100">
  <StackLayout [top]="myTop$ | async" height="30" backgroundColor="#faebd7" width="100%" verticalAlignment="center">
    <Label [text]="'abc'"></Label>
    <StackLayout class="hr-light"></StackLayout>
  </StackLayout>
</AbsoluteLayout>

public myTop$:Observable<Number> = interval(1000).pipe(map((animationIndex)=>{
          return animationIndex%100; // top range 0->100
      }),share());

However, when i put these codes in *ngFor for more animations, it seems that nothing happens. For example :

  <template *ngFor="let item of objList ; let i=index ">
    <StackLayout [top]="myTop$ | async" height="30" backgroundColor="#faebd7" width="100%" verticalAlignment="center">
      <Label [text]="item.label"></Label>
      <StackLayout class="hr-light"></StackLayout>
    </StackLayout>
  </template>

How can i make it work as expected?

标签: angularrxjsnativescript

解决方案


感谢大家帮助纠正我的错误。

但是,在我将 'ng-template' 替换为 'ng-container' 之前,它仍然无法工作。

为了排除 nativescript 的干扰,我也可以在纯 angular6 环境下重现这个问题。

我知道“ng-template”和“ng-container”的区别。有什么解释吗?


推荐阅读