将样式设置仅应用于使用*ngFor创建的第一个元素

3

我正在使用以下代码来显示某些数量的*字符

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

我希望只给第一个设置边距。我想将边距绑定到相应的.ts文件中的marginVar变量中。
这是如何将边距设置为所有元素的方法。
[style.margin-left.px]="marginVar"

我该如何将其应用到仅由*ngFor创建的第一个元素?

1
Did you try using ngIf? - Sanchit Patiyal
{btsdaf} - sanjihan
{btsdaf} - Sanchit Patiyal
2个回答

14

ngFor提供了first

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

或使用CSS

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

有关所有*ngFor变量,请参见:

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


1
如果您转而使用CSS类,则很简单:
[class.first]="i === 0"

否则使用 ngIf (ngIfThen/ngIfElse)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接