我正在开发App服务器认证和数据库搜索引擎的动态风格元素功能。
当
searchNoResult
,UI是。
当点击按钮触发
execSearch()
事件 ->searchSuccess
为真,并且模板searchSuccessColor
生效(文本背景颜色变成粉红色)。 然而,我似乎不能让颜色动态地风格化。
我试着把模板设置成下面的样子,但是没有用。
<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>
我用了下面的组件方法,但没有效果。
setColor() {
return this.searchSuccess === true ? 'pink' : 'black';
}
谁能帮我找出问题所在?
如果只用 else 块来给背景着色,那么可以完全跳过它,用 [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>
如果你不希望对颜色值进行硬编码,你可以尝试在控制器中定义一个变量来保存颜色值。
控制器
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
在这里,它表示控制器中的变量。它表示控制器中的变量。单引号的值,如 'pink'
表示字符串的字数。
ngClass
CSS
.highlight-pink {
background-color: pink;
}
.highlight-black {
background-color: black;
color: white;
}
模板
<div [ngClass]="searchSuccess ? 'highlight-pink' : 'highlight-black'">
<p>{{ stateSearchResult }}</p>
</div>