Home > Net >  How to apply multiple object property to ngStyle
How to apply multiple object property to ngStyle

Time:12-04

I have an element in my HTML like this: <span [ngStyle]="{'background': getColor(selectedOption.type)}">BLAH</span>

I have a condition in my TS file like this:

public getColor(type: string){

        switch (type) {
        case 'General':
            return {background: '#ffe5d7', color: '#e7560a' };
        case 'Interview':
            return { background: '#ffe5d7', color: '#e7560a' };
//more code

Basically, if the user selects "General", I want the correct background AND font color to be returned from the function and applied to the element using ngStyle. But this isn't working correctly. What am I doing wrong?

CodePudding user response:

Try this:

<span [ngStyle]="getColor(selectedOption?.type)">BLAH</span>

public getColor(type: string | undefined){

   if (type) {

      switch (type) {
        case 'General':
            return {background: '#ffe5d7', color: '#e7560a' };
        case 'Interview':
            return { background: '#ffe5d7', color: '#e7560a' };
        //more code

        case default:
            return {};
 
   }

return {};
}

  

EDIT: I've just read @Onur Baştürk had answerd before me. He was right, you were duplicating the background attribute, one in the HTML ([ngStyle]="{'background':...) and another in your ts code:

return {background: '#ffe5d7', color: '#e7560a' ....
  • Related