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

set style to only first element created with *ngFor

我正在使用以下代码显示一些 * 个字符

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

我只想给第一个设置边距。我希望边距绑定到相应 .ts 文件中的 marginVar 变量。

这就是我为所有元素设置边距的方式。

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

如何将它仅应用于使用 *ngFor 创建的第一个元素?

如果你改用 css 类 那就很简单了:

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

否则玩 ngIf (ngIfThen/ngIfElse).

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