简体   繁体   English

使用 ngStyle 指定备用背景图像

[英]Specifying alternate background image using ngStyle

I am trying to specify an alternate background image for a DIV like so:我正在尝试为 DIV 指定备用背景图像,如下所示:

<div [ngStyle]="{'background-image':'url(1.jpg), url(2.jpg)'}"></div>

Neither of the images are displaying (it works if I don't specify an alternate image).两个图像都没有显示(如果我不指定备用图像,它会起作用)。

Is it possible to specify multiple background images using ngStyle ?是否可以使用ngStyle指定多个背景图像?

Working demo工作演示

Template file模板文件

  <div  [ngStyle]='styles'>
      <h1>Lorem Ipsum Dolor</h1>
      <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
      </div>

Ts file ts文件

 export class AppComponent  {

  name = 'Angular';
  img1 = 'https://www.w3schools.com/css/img_flwr.gif';
  img2 = 'https://www.w3schools.com/css/paper.gif'
  isSelected: boolean =  true;
  styles = {};


  setCurrentStyles() {
    this.styles = { 
        backgroundImage: this.isSelected ?
                        `url(${this.img1})`:`url(${this.img2})`
    };
  }

  toogleImage() {
    this.isSelected = !this.isSelected;
    this.setCurrentStyles();
  }
}

Try like this像这样试试

template.html模板.html

<div class="image" [ngStyle]="{background: !isActive ? 'url(https://www.fonewalls.com/wp-content/uploads/Aqua-Solid-Color-Background-Wallpaper-for-Mobile-Phone.png)' : 'url(https://www.fonewalls.com/wp-content/uploads/Midnight-Blue-Solid-Color-Background-Wallpaper-for-Mobile-Phone.png)'}"></div>

cmponent.ts组件.ts

  isActive: boolean = true;

You can also keep your HTML clean with moving all the logic into the component.ts.您还可以通过将所有逻辑移动到 component.ts 中来保持 HTML 干净。

In the end you would have something like this:最后你会得到这样的东西:

<div class="image" [ngStyle]="{
  'background-image': 'url(' + backgroundImageString + ')'
}"></div>

Then in your component:然后在您的组件中:

private defineBackImage(someArg) {
  if (stuff) {
    this.backgroundImageString = url1;
  } else {
    this.backgroundImageString = url2;
  }
}

You can trigger this function on init of according to specific events, also you can extend this logic to display much more than 2 backgrounds您可以根据特定事件在初始化时触发此 function,也可以扩展此逻辑以显示超过 2 个背景

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM