基于动态值的角度变化图像

时间:2019-04-16 12:15:02

标签: angular ionic-framework ionic3

这是我的下面的代码

只有在其他条件我想做的情况下我才在做,否则如果基于三个值的条件我想更改图像

<img [src]="status.getRequestStatus() == 'granted' ? 'assets/imgs/trafficlight_green.png':'assets/imgs/trafficlight_red.png' " class="image--background" >

这是针对if and else条件,我想添加if else if if

if(new){someimage}else if(new1){some image1} if(new2){some image2}

4 个答案:

答案 0 :(得分:1)

您可以在以下条件下使用多个img标签-

<img *ngIf="new" [src]="assets/imgs/trafficlight_green1.png" class="image--background">
<img *ngIf="new1" [src]="assets/imgs/trafficlight_green2.png" class="image--background">
<img *ngIf="new2" [src]="assets/imgs/trafficlight_green3.png" class="image--background">

或者使用变量将图像源存储在component.ts中,然后按如下所示将其绑定在component.html中-

<img [src]="imageSource" class="image--background">

答案 1 :(得分:1)

如果要使用if else流,可以将三元语句保留在模板中,因为可以将三元链接起来。看起来可能是这样。

<img [src]="'new' ? 'green.png': new1 ? 'red.png' : 'amber.png'" class="image-background">

这看起来像

if (new)
{ 'green.png' }

else if (new1)
{ 'red.png' }

else 
{ 'amber.png' } // being new2

希望这就是您想要的。

答案 2 :(得分:0)

将逻辑移至组件。

在您的component.html

<img [src]="someFn()" class="image--background" >

在您的component.ts

someFn() {
    let rtn = '';
    if(...) {
        rtn = ...
    } else if (...) {
       ...
    } else {
       ...
    }
    return rtn;
}

答案 3 :(得分:0)

根据我的评论尝试此解决方案:

检查StackBlitz上的示例

验证是在组件上进行的,在您的getRequestStatus()上,我使用ngOnInit进行超时,以“动态”更改

源将根据源属性更改自动更新。

视图:

<img [(src)]="sourceImage" width="200" />

组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  sourceImage: string;

  ngOnInit() {
    this.sourceImage = 'https://angular.io/assets/images/logos/angular/angular.svg';

    setTimeout(()=> {
        this.sourceImage = 'https://dwglogo.com/wp-content/uploads/2017/03/AngularJS_logo_004.svg';
    }, 2000)
  }
}
相关问题