【问题标题】:Angular 2 - background image into a html file using ngStyleAngular 2 - 使用 ngStyle 将背景图像转换为 html 文件
【发布时间】:2016-09-26 05:55:54
【问题描述】:

我正在使用 Angular 2 服务从 API 中提取数据。我可以使用类似于 {{ project.title }} 的东西将 json api 中的所有内容输出到页面上,但是我希望将 url 输出到后台图像,我似乎无法让它工作..有没有人有任何想法或建议?

目前这就是我所拥有的。我也试过不带花括号,但没有任何效果。

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

【问题讨论】:

    标签: angular angular2-template angular2-services angular2-directives


    【解决方案1】:

    不要同时使用[]{{}},要么一个,要么另一个:

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

    另见In RC.1 some styles can't be added using binding syntax

    【讨论】:

    • 对此仍然不满意..它让我不确定
    • 是我还是其他人对 Angular 2 有点失望......它承诺了很多,但即使是最微不足道的事情也需要很多步骤才能做到正确
    【解决方案2】:

    你不需要使用 {{}} 来调用一些属性而不是你在指令中输入的内容,如下所示:

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

    您可以在此Plunker 中查看示例。享受吧。

    【讨论】:

    • 或者只是将对象传递给 ngStyle,例如:[ngStyle]="backgroundStyle"
    【解决方案3】:

    只是建立在 Gunter 的回答之上,这也适用于异步管道。

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

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2017-08-30
      • 2020-06-24
      • 2018-10-12
      • 2016-04-24
      • 2019-11-26
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多