【问题标题】:ngStyle to ngClass functionngStyle 到 ngClass 函数
【发布时间】:2022-12-14 04:23:25
【问题描述】:

我想将我的 ngStyle 条件更改为 ngClass 条件,向其添加一个 function() 以在另外 2 个 div 中添加该函数

.html

[ngStyle]="{'background-color': rl.selected ? '#0084c5' : '',
             fontWeight: rl.selected ? '500' : '300'}"

(click)="getRowsStyle(rl.name)"

<span [ngClass]="{ color: rl.selected ? 'white' : 'black' }">{{ rl.name }}</span>

.ts


    changeColor(filter){
        if  (filter.selected) {
            return "background-color: black"
        } else {
            return "background-color: white"
        }

我希望添加一个 ngClass 并在内部添加一个函数在选择时动态更改颜色,用它替换 ngStyle 条件。

【问题讨论】:

    标签: css angular typescript ng-class ng-style


    【解决方案1】:

    您应该使用指令而不是使用 ngClass 并添加一个方法来返回 ngClass 的值。

    @Directive({
      selector: '[appSelectedBackground]',
    })
    export class SelectedBackgroundDirective {
      @Input() set appSelectedBackground(isSelected: boolean) {
        if (isSelected) {
          this.elementRef.nativeElement.style.background = 'black';
        } else {
          this.elementRef.nativeElement.style.background = 'white';
        }
      }
      constructor(private elementRef: ElementRef) {}
    }
    
    <div [appSelectedBackground]='rl.selected'>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-14
      • 2018-08-28
      • 2020-04-30
      • 2018-05-02
      • 2016-07-17
      • 2021-11-14
      • 2018-10-18
      • 1970-01-01
      相关资源
      最近更新 更多