Angular 4 background style when using ngFor

I have a problem with the background image url. I have an array of image urls, how can I use it in the background image url

<div class="col-lg-3 col-md-3 col-sm-6" *ngFor="let course of courses"><a>
    </a><div class="box"><a>
        <div class="box-gray aligncenter"  [style.backgroundColor]="course.imageUrl" >
        </div>
        </a><div class="box-bottom"><a >
            </a><a >{{course.name}}</a>
        </div>
    </div>
</div>
+14
source share
6 answers

Refer to this Angular2 Dynamic Background Image

// inappropriate style.backgroundColor 
[style.backgroundColor]="course.imageUrl"

// style.backgroundImage
[style.backgroundImage]="'url('+ course.imageUrl +')'"
+38
source

You should use backgroundinsteadbackgroundColor

[style.background]="'url('+course.imageUrl+')'"
+7
source

,

[ngStyle]="{'background-image':'url(' + course.imageUrl + ')'}">
+7

, URL- .

bgImageVariable="www.domain.com/path/img.jpg";

second way
[ngStyle]="{'background-image': 'url(' + bgImageVariable + ')'}"
+2

URL- , ngFor, [src].

<div class="col-lg-3 col-md-3 col-sm-6" *ngFor="let course of courses"><a>
    </a><div class="box"><a>
        <div class="box-gray aligncenter"  >
           <img [src]="course.imageUrl" />
        </div>
        </a><div class="box-bottom"><a >
            </a><a >{{course.name}}</a>
        </div>
    </div>
</div>
0

, URL , .

, , URL- , , .

, Javascripts, encodeURI().

, .

. :

///-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.module.ts

import { EncodeUriPipe } from './pipes/encode-uri.pipe';
...

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule
    ...
  ],
  exports: [
    ...
  ],
 declarations: [
    AppComponent,
    EncodeUriPipe
 ],
 bootstrap: [ AppComponent ]
})

export class AppModule { }

SRC/ /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';
  }
}

/ /app.component.html

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

Source: https://habr.com/ru/post/1679165/


All Articles