Home > Mobile >  ngStyle to ngClass function
ngStyle to ngClass function

Time:12-06

I want to change my ngStyle conditional to ngClass condition adding a function() to it to add the function in 2 more divs

.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"
        }

I expected to add a ngClass and inside add a function do dynamically change the color when selected, replacing the ngStyle conditional with it.

Thank you.

CodePudding user response:

You should use a directive instead of using a ngClass and adding a method to return values for 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>
  • Related