简体   繁体   English

Angular 2-使用ngStyle将背景图像转换为html文件

[英]Angular 2 - background image into a html file using ngStyle

I am pulling data from an API using an Angular 2 service.. I can output everything from the json api onto the page using something similar to this {{ project.title }} however i wish to output the url to a background image and I cant seem to get it working.. has anyone got any ideas or advice ? 我正在使用Angular 2服务从API提取数据。我可以使用类似于{{project.title}}的东西将所有内容从json api输出到页面上,但是我希望将URL输出到背景图片,我似乎无法正常工作..有人有任何想法或建议吗?

Currently this is what I have. 目前这就是我所拥有的。 I've tried it without the curly braces also but nothing is working. 我也没有花括号试过,但没有任何效果。

<div class="table-wrap featuredimg"  [ngStyle]="{'background-image': 'url(' + {{ project.projectimage }} + ')'}">

You don't need use {{}} for call some propiety than you put in a directive, like this: 您不需要使用{{}}来调用某些属性,而不必像在指令中这样放置:

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

@Component({
  selector: 'my-app',
  template: `
<div class="image" [ngStyle]="{'background-image':'url(' + object.link + ')'}"></div>
  `,
  styles: [`
  .image{width:100px;height:100px; border: solid 1px black;}
  `]
})
export class AppComponent {
  selectedColor:any = 0;
  color;

  object = {
    link: "http://lorempixel.com/100/100"
  }

  constructor(){
  }
}

You can see the example in this Plunker . 您可以在此Plunker中看到示例。 Enjoy. 请享用。

Don't use [] and {{}} together, it's either the one or the other: 请勿同时使用[]{{}} ,它们是其中之一:

<div class="table-wrap featuredimg"  [ngStyle]="{'background-image': 'url(' + project.projectimage + ')'}">

See also In RC.1 some styles can't be added using binding syntax 另请参见在RC.1中,无法使用绑定语法添加某些样式

Just to build on top of Gunter's answer, this works with the async pipe as well. 只是基于Gunter的答案,这也适用于异步管道。

 <div md-card-avatar class="profile_header" 
  [ngStyle]="{'background': 'url(' + (usergravatar$ | async) + ')'}"></div>

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

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