如何在* ngFor中使用Observable变量

时间:2018-07-02 08:42:34

标签: angular rxjs nativescript

我在本机脚本角度应用程序中使用rxjs。 就我而言,我通过使用可观察变量'myTop$'设置StackLayout的顶部来实现一个简单的动画。以下代码可以正常工作,并且"StackLayout"会按预期移动:

<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());

但是,当我将这些代码放在*ngFor中以获取更多动画时,似乎什么也没发生。例如:

  <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>

我如何使其按预期工作?

3 个答案:

答案 0 :(得分:0)

只需使用ng-template代替template,因为在angular 6中不存在模板。

示例:

<ng-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>
  </ng-template>

答案 1 :(得分:0)

您需要使用“ ng-template”代替“ template”

<ng-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>
  </ng-template>

答案 2 :(得分:0)

感谢您的帮助以纠正我的错误。

但是,直到我将“ ng-template”替换为“ ng-container”,它仍然无法工作。

为了消除对原语的干扰,我还可以在纯angular6环境中重现此问题。

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