How to add background-image using ngStyle (angular2)?

前端 未结 9 2210
青春惊慌失措
青春惊慌失措 2020-11-28 05:36

How to use ngStyle to add background-image? My code doesn\'t work:

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


        
9条回答
  •  再見小時候
    2020-11-28 05:50

    Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

    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 + ')');
      }
    
    }

提交回复
热议问题