【问题标题】:How to add background-image using ngStyle (angular2)?如何使用 ngStyle (angular2) 添加背景图像?
【发布时间】:2016-04-24 20:18:00
【问题描述】:

如何使用 ngStyle 添加背景图片? 我的代码不起作用:

this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg';

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

【问题讨论】:

标签: javascript html css angular


【解决方案1】:

我的解决方案,使用 if..else 语句。如果您想避免不必要的挫折,检查您的变量是否存在并已设置,这始终是一个好习惯。否则,提供备用图片以防万一;还可以指定多个样式属性,如background-position: center等

&lt;div [ngStyle]="{'background-image': this.photo ? 'url(' + this.photo + ')' : 'https://placehold.it/70x70', 'background-position': 'center' }"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    大多数情况下,图像不会显示,因为您的 URL 包含空格。 在你的情况下,你几乎做的一切都是正确的。除了一件事 - 如果您在 css 中指定背景图像,您没有像添加单引号那样添加单引号 IE。

    .bg-img {                \/          \/
        background-image: url('http://...');
    }
    

    通过 \' 转义 HTML 中的引号字符

                                              \/                                  \/
    <div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
    

    【讨论】:

      【解决方案3】:

      您可以使用两种方法:

      方法一

      <div [ngStyle]="{'background-image': 'url(&quot;' + photo + '&quot;)'}"></div>
      

      方法二

      <div [style.background-image]="'url(&quot;' + photo + '&quot;)'"></div>
      

      注意:用 " 字符包围 URL 很重要。

      【讨论】:

        【解决方案4】:

        我的背景图片不起作用,因为 URL 中有一个空格,因此我需要对其进行 URL 编码。

        您可以通过尝试不包含需要转义的字符的其他图片 URL 来检查是否是您遇到的问题。

        您可以仅使用内置于 encodeURI() 方法的 Javascript 对组件中的数据执行此操作。

        我个人想为它创建一个管道,以便它可以在模板中使用。

        为此,您可以创建一个非常简单的管道。 例如:

        src/app/pipes/encode-uri.pipe.ts

        import { Pipe, PipeTransform } from '@angular/core';
        
        @Pipe({
          name: 'encodeUri'
        })
        export class EncodeUriPipe implements PipeTransform {
        
          transform(value: any, args?: any): any {
            return encodeURI(value);
          }
        }
        

        src/app/app.module.ts

        import { EncodeUriPipe } from './pipes/encode-uri.pipe';
        ...
        
        @NgModule({
          imports: [
            BrowserModule,
            AppRoutingModule
            ...
          ],
          exports: [
            ...
          ],
         declarations: [
            AppComponent,
            EncodeUriPipe
         ],
         bootstrap: [ AppComponent ]
        })
        
        export class AppModule { }
        

        src/app/app.component.ts

        import {Component} from '@angular/core';
        
        @Component({
          // tslint:disable-next-line
          selector: 'body',
          template: '<router-outlet></router-outlet>'
        })
        export class AppComponent {
          myUrlVariable: string;
          constructor() {
            this.myUrlVariable = 'http://myimagewith space init.com';
          }
        }
        

        src/app/app.component.html

        <div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>
        

        【讨论】:

          【解决方案5】:

          改用

          [ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"
          

          【讨论】:

            【解决方案6】:

            看起来您的样式已经过清理,要绕过它,请尝试使用 DomSanitizer 中的 bypassSecurityTrustStyle 方法。

            import { Component, OnInit, Input } from '@angular/core';
            import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
            
            @Component({
              selector: 'my-component',
              templateUrl: './my-component.component.html',
              styleUrls: ['./my-component.component.scss']
            })
            
            export class MyComponent implements OnInit {
            
              public backgroundImg: SafeStyle;
              @Input() myObject: any;
            
              constructor(private sanitizer: DomSanitizer) {}
            
              ngOnInit() {
                 this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');
              }
            
            }
            &lt;div *ngIf="backgroundImg.length &gt; 0" [style.background-image]="backgroundImg"&gt;&lt;/div&gt;

            【讨论】:

              【解决方案7】:
              import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
              
                constructor(private sanitizer:DomSanitizer) {
                  this.name = 'Angular!'
                  this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
                }
              
              <div [style.background-image]="backgroundImg"></div>
              

              另见

              【讨论】:

                【解决方案8】:

                你也可以试试这个:

                [style.background-image]="'url(' + photo + ')'"

                【讨论】:

                • @redfox05 我想 ngStyle 是一种语法糖。主要区别在于 ngStyle 允许你应用多个 css 规则,但 [style.] 只允许一个。接下来是等价的:&lt;div [ngStyle]="{ color: 'red', 'font-size': '22px' }"&gt;First&lt;/div&gt; 和 &lt;div [style.color]="'red'" [style.font-size.px]="22"&gt;Second&lt;/div&gt;
                • 我使用了这个 [style.css] 方法,虽然我无法让 [style.background-repeat] 工作,你知道为什么吗?
                • 如何使用这种方法进行条件样式设置?假设我要检查照片是否不为空,然后只应用这种样式?
                【解决方案9】:

                我想你可以试试这个:

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

                通过阅读您的ngStyle 表达式,我猜您错过了一些“'”...

                【讨论】:

                • 经过测试。使用 RC.1。根据他们所说的here,RC.2 和更新版本不需要它
                • 我更喜欢this.photo = `url(${photo})`; [style.background-image]='photo'。
                • 请记住,图片 URL(图片名称)中的空格可能会导致静默 [ngStyle] 和 [style.background-image] 呈现失败。
                • 这很好。我曾经使用过它并且效果很好。不错?
                猜你喜欢
                • 2018-10-12
                • 1970-01-01
                • 1970-01-01
                • 2020-08-26
                • 2019-11-26
                • 2018-02-12
                • 2014-10-17
                • 2021-09-05
                • 2015-09-17
                相关资源
                最近更新 更多