0

I have a function carDateCalculator which returns true or false according to parameter it recieves.Here what I tried to change background but didnt work.I get template parse Error.If function returns true I'll change the background color as red otherwise nothing will happen

Here what I tried

<span [ngStyle]="{ carDateCalculator(car.Date) ? {'background-color': 'red'} }">
0

5 Answers 5

1

Setting styles using NgStyle works as key:value pair. key is the style property name and value is the style value.

You were using the conditional wrongly, use this instead to set color to red when function returns true else don't set.

<span [ngStyle]="{ 'background-color': carDateCalculator(car.Date) ? 'red': '' }">Some text</span>

Sign up to request clarification or add additional context in comments.

Comments

1

Do like this:

<span [ngStyle]="{ 'background-color': carDateCalculator(car.Date) ? 'red': 'black' }">

Comments

1

Update the conditional NgStyle like this:

<span [ngStyle]="{ 'background-color': carDateCalculator(car.Date) ? 'red': '' }">

The format is like:

[ngStyle]="{ 'property-name': property-value }"

Comments

1

Try this

You are using wrong syntax. Property name should come first than the condition which you want to check Try this

.ts

export class AppComponent  {
  value = 1;
  carDateCalculator(value){
   return value === 1 ? true : false
  }
}

.html

<span [ngStyle]="{'background-color': carDateCalculator(value) ? 'red' : ''}">Some example text</span>

Comments

0

Creating pipe carDateCalculatorPipe which would set that style itself would be better in performance as it stops after matching.

Methods inside of components are setting up process which is continuously updating that condition.

Check both with console.log, you will see the difference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.