Angular - How to apply [ngStyle] conditions

后端 未结 4 930
孤街浪徒
孤街浪徒 2021-02-01 01:00

I have a div that I want to style based on a condition.

If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blu

相关标签:
4条回答
  • 2021-02-01 01:38
    <ion-col size="12">
      <ion-card class="box-shadow ion-text-center background-size"
      *ngIf="data != null"
      [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">
    
      </ion-card>
    
    0 讨论(0)
  • 2021-02-01 01:48
    [ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"
    
    0 讨论(0)
  • 2021-02-01 01:53

    For a single style attribute, you can use the following syntax:

    <div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
    

    I assumed that the background color should not be set if neither style1 nor style2 is true.


    Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

    <div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
    
    0 讨论(0)
  • 2021-02-01 02:01

    You can use an inline if inside your ngStyle:

    [ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"
    

    A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

    [style.background-color]="myColorVaraible"
    
    0 讨论(0)
提交回复
热议问题