My background image didn’t work because there was a space in the URL and therefore I needed to encode it.
You can check if this is your problem by trying a different image url that doesn't have characters to be escaped.
You can do this with the data in the component simply by using Javascripts built into the encodeURI () method.
Personally, I wanted to create a channel for it so that it could be used in the template.
For this you can create a very simple pipe. For example:
SIC / application / pipes / code-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'; } }
SIC / application /app.component.html
<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>
Tom Benyon Jun 12 '19 at 14:48 2019-06-12 14:48
source share