Combine [NgStyle] With Condition (if..else)

前端 未结 10 1426
暗喜
暗喜 2020-12-04 20:55

I have read NgStyle Documentation For Angular 2, and it is a little bit confusing for me. How do I use NgStyle with condition like (if...else) to set background image of any

相关标签:
10条回答
  • 2020-12-04 21:37

    The previous answers did not work for me, so I decided to improve this.

    You should work with url(''), and not with value.

    <li *ngFor="let item of items">
      <div
        class="img-wrapper"
        [ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
      </div>
    </li>
    
    0 讨论(0)
  • 2020-12-04 21:42

    You can use this as follows:

    <div [style.background-image]="value ? 'url(' + imgLink + ')' : 'url(' + defaultLink + ')'"></div>
    
    0 讨论(0)
  • 2020-12-04 21:46

    [ngStyle] with condition based if and else case.

    <label for="file" [ngStyle]="isPreview ? {'cursor': 'default'} : {'cursor': 'pointer'}">Attachment

    0 讨论(0)
  • 2020-12-04 21:48
    Trying to set background color based on condition:   
    
    Consider variable x with some numeric value.    
    <p [ngStyle]="{ backgroundColor: x > 4 ? 'lightblue' : 'transparent' }">
            This is a sample Text
    </p>
    
    0 讨论(0)
  • 2020-12-04 21:49

    Use:

    [ngStyle]="{'background-image': 'url(' +1=1 ? ../../assets/img/emp-user.png : ../../assets/img/emp-default.jpg + ')'}"
    
    0 讨论(0)
  • 2020-12-04 21:50
    <h2 [ngStyle]="serverStatus == 'Offline'? {'color': 'red'{'color':'green'}">Server with ID: {{serverId}} is {{getServerStatus()}} </h2>
    

    or you can also use something like this:

    <h2 [ngStyle]="{backgroundColor: getColor()}">Server with ID: {{serverId}} is {{getServerStatus()}}</h2>
    

    and in the *.ts

    getColor(){return this.serverStatus === 'Offline' ? 'red' : 'green';}
    
    0 讨论(0)
提交回复
热议问题