【问题标题】:Binding variable binds as null when bind using ngStyle使用 ngStyle 绑定时,绑定变量绑定为 null
【发布时间】:2017-05-31 22:22:36
【问题描述】:
我正在尝试使用 ngStyle 设置背景图片,
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }">
类别为一个词时有效,但有两个词时无效,绑定为null
例如,当它作为“一级方程式”出现时,它绑定为 null。什么问题?
【问题讨论】:
标签:
angular
typescript
ng-style
【解决方案1】:
带有空格的 URL 不会被直接解释,
试试这个,
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="alertStyles">
在组件中,
alertStyles = {
'background-image': 'url(../imgs/banner/' + this.event?.category.replace(" ", "%20") + '.jpg)'
};
例子:
@Component({
selector: 'app-style-example',
template: `
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="alertStyles">
`
})
export class StyleExampleComponent {
alertStyles = {
'background-image': 'url(../imgs/banner/' + this.event?.category.replace(" ", "%20") + '.jpg)'
};
}
编辑:如果你正在循环事件,你应该传递事件参数
@Component({
selector: 'app-style-example',
template: `
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="changeStyle(event)">
`
})
export class StyleExampleComponent {
}
changeStyle(event) {
return {
'background-image': 'url(../imgs/banner/' + event?.category.replace(" ", "%20") + '.jpg)'
}
}