javascript - Angular ngStyle 带有 ngIf 的动态样式元素

标签 javascript angular styling angular-directive angular-template

我正在应用程序服务器身份验证和数据库搜索引擎中开发动态样式元素功能。

When searchNoResult, UI is:

enter image description here

When click the button triggering execSearch() event -> searchSuccess is true and template searchSuccessColor takes effect (text backgroundColor turns pink). However, I can’t seem to get the color dynamically styled:

enter image description here

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/

相关文章:

javascript - 如何在 ember.js 中创建一个寄存器?存储.createRecord

Angularfire2读取数据一次

angular - 类不是 Angular 模块 - 仅在 IntelliJ/Webstorm 中导入本地构建 Angular 库时

javascript - 导入第三方javascript到vuejs

javascript - 如何跨 HTML go-gin 的所有 js 文件访问变量

css - 需要将 Pinterest 板向右浮动

c++ - Qt:编辑条目时 QtAbstractItemView (QTableView) 的背景

css - GWT 样式单元格表头

javascript - jQuery - 将类添加到最近的音频播放器上方的 Div

Angular 使用带有@HostListener 的指令来更新 ReactiveForm 的输入值是将输入设置为 ngValid 而不是 ngInvalid