【问题标题】:Background image in Angular 2Angular 2 中的背景图片
【发布时间】:2018-01-19 17:18:09
【问题描述】:

如何通过 ngOnInit 将图片添加到背景中? 我不想在 CSS 中使用background: url("link of my image"),因为这会增加我网站的负载。我想通过 Angular 2 Typescript 来做到这一点

【问题讨论】:

  • 据我所知,在 css 中完成的样式比在 js 中完成的更快。
  • 真的吗?我的登陆加载所有,然后我看到图像和登录表单。我需要加载登录表单并同时加载图片

标签: javascript html css angular


【解决方案1】:

在你的component.ts中,导入DomSanitizer,

从“@angular/platform-b​​rowser”导入 { DomSanitizer };

...在你的组件类中删除一个变量,比如backgroundImageStyle并在ngOnInit中初始化这个变量:

backgroundImageStyle: string; 

constructor(private sanitizer: DomSanitizer) { }

public ngOnInit()
{
    this.backgroundImageStyle = this.getBackgroundImageStyle();
}

private getBackgroundImageStyle()
{
    let backgroundImage = './path/to/your/image';

    // sanitize the style expression
    const style = `background-image: url(${backgroundImage})`;
    return this.sanitizer.bypassSecurityTrustStyle(style);
}

在你的组件 html 中,设置你的主容器的样式属性:

[style]="backgroundImageStyle"

【讨论】:

    【解决方案2】:

    你想的没错!它可以通过多种方式完成!

    1) 通过改变样式输入:

    import {Component} from '@angular/core'
    import { DomSanitizer  } from '@angular/platform-browser';
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <div [style]="getStyle()">
            I am a div that wants to be styled
          </div>
          <button (click)="showStyle = !showStyle;">Toggle style</button>
        </div>
      `
    })
    export class App {
      showStyle: false;
    
      constructor() {
      }
    
      getStyle() {
        // snip snip -> fetch the url from somewhere
        const profilePicUrl = 'some-remote-server-url.jpg';
        const style = `background-image: url(${profilePicUrl})`;
        // sanitize the style expression
        return this.sanitizer.bypassSecurityTrustStyle(style);
      }
    }
    

    2) 通过改变 ngClass:

    然后在 ngOnInit() 中设置你想要的变量

    3) 通过添加指令:

    import {Directive, ElementRef, Renderer} from '@angular/core';
    
    @Directive({
      selector: '[setBackgroundImage]',
    })
    export class StyledDirective {
      constructor(public el: ElementRef, public renderer: Renderer) {
        // el.nativeElement.style.backgroundColor = 'yellow';
        renderer.setElementStyle(el.nativeElement, 'backgroundImage', 'yourImageLink');
      }
    }
    

    以及此来源中的许多其他方式,例如: https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2018-10-23
      • 2020-03-28
      相关资源
      最近更新 更多