Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set style to only first element created with *ngFor

I am using the follwing code to display some number of * characters

  <div *ngFor="let line of lines;let i=index">*</div>

I would like to set a margin only to the first one. I want the margin to be bound to a marginVar variable inside coresponding .ts file.

This is how I would set margin to all of the elements.

[style.margin-left.px]="marginVar"

How can I apply it to only the first element created with *ngFor?

like image 938
sanjihan Avatar asked Dec 08 '25 06:12

sanjihan


2 Answers

ngFor provides first

<div *ngFor="let line of lines;let i=index; first as isFirst"
    [style.margin-left.px]="isFirst ? marginVar : 0">*</div>

or using CSS

<div *ngFor="let line of lines;let i=index; first as isFirst"
    [class.first]="isFirst">*</div>

For all *ngFor variables see

https://angular.io/api/common/NgForOf#local-variables

like image 64
Günter Zöchbauer Avatar answered Dec 09 '25 19:12

Günter Zöchbauer


If you switch to using css classes then it is straightforward:

[class.first]="i === 0"

Otherwise play with ngIf (ngIfThen/ngIfElse).

like image 40
kemsky Avatar answered Dec 09 '25 19:12

kemsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!