我正在应用程序服务器身份验证和数据库搜索引擎中开发动态样式元素功能。
When
searchNoResult
, UI is:
When click the button triggering
execSearch()
event ->searchSuccess
is true and templatesearchSuccessColor
takes effect (text backgroundColor turns pink). However, I can’t seem to get the color dynamically styled:
I tried setting the template as below but doesn't work:
<button class="button"
[disabled] = "!enableSearch"
(click) = "execSearch()">Search State</button>
<div *ngIf = "searchSuccess; then searchSuccessColor else searchNoResult"></div>
<ng-template #searchNoResult>
<p>{{ stateSearchResult }}</p>
</ng-template>
<ng-template #searchSuccessColor>
<div [ngStyle]="{backgroundColor: 'pink'}"></div>
<p>{{ stateSearchResult }}</p>
</ng-template>
I tired component method as below but doesn't work:
setColor() {
return this.searchSuccess === true ? 'pink' : 'black';
}
有人可以帮忙找出问题所在吗?
最佳答案
如果 else block 仅用于为背景着色,则可以使用 [style.background-color]
和三元运算符完全跳过它。尝试以下方法
<div [style.background-color]="searchSuccess ? 'pink' : ''"><p>{{ stateSearchResult }}</p></div>
或者如果您想使用ngStyle
(也许要包含更多样式),那就是
<div [ngStyle]="{'background-color': searchSuccess ? 'pink' : ''}"><p>{{ stateSearchResult }}</p></div>
或者您也可以使用 ngClass
有条件地包含 CSS 选择器。
app.component.css
.highlight {
background-color: pink;
}
app.component.html
<div [ngClass]="{highlight: searchSuccess}"><p>{{ stateSearchResult }}</p></div>
更新:使用 Controller 中定义的变量
如果您不希望对颜色值进行硬编码,您可以尝试在 Controller 中定义一个保存颜色值的变量。
Controller
export class AppComponent implements OnInit {
backgroundColor = 'pink';
// button `click` event handler
execSearch() {
...
this.backgroundColor = searchSuccess ? 'pink' : 'black';
}
}
模板
<div [style.background-color]="backgroundColor">
<p>{{ stateSearchResult }}</p>
</div>
<div [ngStyle]="{'background-color': backgroundColor}">
<p>{{ stateSearchResult }}</p>
</div>
请注意此处 backgroundColor
周围缺少单引号。它表示 Controller 中的变量。像 'pink'
这样的单引号值表示字符串文字。
ng类
CSS
.highlight-pink {
background-color: pink;
}
.highlight-black {
background-color: black;
color: white;
}
模板
<div [ngClass]="searchSuccess ? 'highlight-pink' : 'highlight-black'">
<p>{{ stateSearchResult }}</p>
</div>
关于javascript - Angular ngStyle 带有 ngIf 的动态样式元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62397067/