我的背景图片不起作用,因为 URL 中有一个空格,因此我需要对其进行 URL 编码。
您可以通过尝试不包含需要转义的字符的其他图片 URL 来检查是否是您遇到的问题。
您可以仅使用内置于 encodeURI() 方法的 Javascript 对组件中的数据执行此操作。
我个人想为它创建一个管道,以便它可以在模板中使用。
为此,您可以创建一个非常简单的管道。
例如:
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: '<router-outlet></router-outlet>'
})
export class AppComponent {
myUrlVariable: string;
constructor() {
this.myUrlVariable = 'http://myimagewith space init.com';
}
}
src/app/app.component.html
<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>