How to use Observable variable in *ngFor

Multi tool use
Multi tool use


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 :


rxjs


'myTop$'


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



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


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



How can i make it work as expected?





You probably want to use <ng-container> element instead of <template>
– Florian
Jul 2 at 9:34




3 Answers
3



Just use ng-template instead of template because in angular 6 template is doesn't exists.


ng-template


template



example:


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



You need to use 'ng-template' in the place of '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>



Thanks all for your help to correct my mistake.



However, it still can not work until i replace 'ng-template' with 'ng-container'.



To exclude the distraction of nativescript,I can also reproduce this issue in a pure angular6 environment.



I know feel about the difference of 'ng-template' and 'ng-container'. Any explanation?






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

nXUws4s8T7,OR,OAeV4jK8LtGmckElxtJ,va416MXpSrjFBR84yvBx
hs9 XJTk1BYKT8Z1tNnhyXnk7gP39XcnK1 A1IlC4D6bPUraQFGGmWiPjMxtzxrQi0db2wBq7qK3,qg,ubL

Popular posts from this blog

Rothschild family

Boo (programming language)