How to use ngStyle to add background-image? My code doesn\'t work:
this.photo = \'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg\
My background image wasn't working because the URL had a space in it and thus I needed to URL encode it.
You can check if this is the issue you're having by trying a different image URL that doesn't have characters that need escaping.
You could do this to the data in the component just using Javascripts built in encodeURI() method.
Personally I wanted to create a pipe for it so that it could be used in the template.
To do this you can create a very simple pipe. For example:
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: ' '
})
export class AppComponent {
myUrlVariable: string;
constructor() {
this.myUrlVariable = 'http://myimagewith space init.com';
}
}
src/app/app.component.html