使用ngStyle

时间:2019-11-21 09:49:01

标签: css angular

我试图像这样为DIV指定备用背景图片:

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

这两个图像均未显示(如果我未指定其他图像,则可以使用。)

是否可以使用ngStyle指定多个背景图像?

3 个答案:

答案 0 :(得分:2)

Working demo

模板文件

  <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文件

 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();
  }
}

答案 1 :(得分:0)

尝试这样

template.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

  isActive: boolean = true;

答案 2 :(得分:0)

您还可以通过将所有逻辑移到component.ts中来保持HTML整洁。

最后,您将得到以下内容:

vector<myType>

然后在您的组件中:

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

您可以根据特定事件在初始化时触发此功能,也可以扩展此逻辑以显示2个以上的背景