如何在:nth-child中使用ngStyle?

huangapple go评论70阅读模式
英文:

How to use ngStyle with :nth-child?

问题

<p *ngIf="status"> Secret Password is Tuna</p>
<div *ngFor="let clickLog of clickLogs" [ngStyle]="{'background-color': (clickLog === clickLogs[5] ? 'red' : 'transparent')}">
  {{clickLog}}
</div>
<button (click)="clickEvent()">Show Details</button>
<button [disabled]="!checkIfEmty()" (click)="resetUserName()">Reset Username</button>

在上述代码中,我已经移除了 [ngStyle] 中的 div:nth-child(n+6) 部分,并用条件表达式来为第六个子元素及其后的元素设置背景颜色为红色。

英文:

I am new to Angular, and I am trying to style items after the 6th child but it doesn't work. I can color everything, but when I add the nth-child part it doesn't work. Do I have a wrong syntax?

[ngStyle] = "div:nth-child(n+6){'background-color': 'red'}"

&lt;p *ngIf = &quot;status&quot;&gt; Secret Password is Tuna&lt;/p&gt; 
&lt;div *ngFor=&quot;let clickLog of clickLogs&quot; 
   [ngStyle]=&quot;div:nth-child(n+6){{&#39;background-color&#39;: &#39;red&#39;}}&quot;&gt;
  {{clickLog}} 
&lt;/div&gt;
&lt;button (click)=&quot;clickEvent()&quot;&gt;Show Details&lt;/button&gt;
&lt;button [disabled]=&quot;!checkIfEmty()&quot; (click)=&quot;resetUserName()&quot;&gt;Reser Username&lt;/button&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

以下是翻译好的部分:

你可以在组件的CSS文件中使用伪类。

app.component.css

div:nth-child(n+6) {
  background-color: red;
}

但你需要在模板中为它设置合适的结构。

或者你可以使用ngFor的索引。

app.component.ts

<div *ngFor="let clickLog of clickLogs; index as i" 
   [ngStyle]="{'background-color': i >= 6 ? 'red' : '' }">
  {{clickLog}} 
</div>
英文:

You can use pseudo class in the component CSS file.

app.component.css

div:nth-child(n+6) {
  background-color: red
}

But you should have proper structure for it in template.

Or you can use index of ngFor.

app.component.ts

&lt;div *ngFor=&quot;let clickLog of clickLogs; index as i&quot; 
   [ngStyle]=&quot;{&#39;background-color&#39;: i &gt;= 6 ? &#39;red&#39; : &#39;&#39; }&quot;&gt;
  {{clickLog}} 
&lt;/div&gt;

huangapple
  • 本文由 发表于 2020年1月3日 17:01:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定