使用 ngStyle 绑定时,绑定变量绑定为 null
Binding variable binds as null when bind using ngStyle
我正在尝试使用 ngStyle 设置背景图片,
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }">
category为1个词时有效,2个词时无效,绑定为null
例如,当它作为 "Formula one" 出现时,它绑定为 null。有什么问题?
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)'
}
}
我正在尝试使用 ngStyle 设置背景图片,
<div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }">
category为1个词时有效,2个词时无效,绑定为null
例如,当它作为 "Formula one" 出现时,它绑定为 null。有什么问题?
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)'
}
}