操纵DOM
更改特定div的背景而不是使用document.getElementById('id').style.backgroundImage
的更好方法是什么。
我正在尝试更改背景,因为我更改了我的网址,但我能想到的唯一方法就是使用document.getElementById()
changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/spur-2.jpg')";
break;
... more cases
default:
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/background.jpg')";
}
}
我还尝试了Renderer
依赖,但如何使用此目标定位homeBg
?
this.renderer.setElementStyle(this.elRef.nativeElement, 'background-image', "url(./assets/imgs/spur-2.jpg)");
模板 - 基本上只是一个div
<nav></nav>
<div id="homeBg"></div>
修改
已将我的changeBg()
移至我的sharedService
public changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/spur-2.jpg')");
break;
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/background.jpg')");
}
}
在我的个人资料组件中调用changeBg()
服务
ngOnInit() {
this.sharedService.changeBg(); // is this correct?
}
个人资料模板 - 这样会给我一个错误Cannot read property 'homeBg' of undefined
<div class="home" id="homeBg" [style.background-image]="changeBg?.homeBg"></div>
使用route.param.subscribe()
this.routeSub = this.route.params.subscribe(params => {
this.sharedService.changeBg();
}
答案 0 :(得分:3)
使用绑定和指令是Angular2中的首选方式,而不是命令式DOM操作:
<div [style.background-image]="myService.homeBg"
您需要清理Angular的URL才能接受它。 有关详细信息,请参阅In RC.1 some styles can't be added using binding syntax。
changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/spur-2.jpg')");
break;
... more cases
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle( "url('./assets/imgs/background.jpg')");
}
}
答案 1 :(得分:1)
您可以使用模板引用和@ViewChild
装饰器:
<div #myDiv id="homeBg"></div>
class MyComponent implements AfterViewInit{
@ViewChild("myDiv")
elRef:ElementRef
ngAfterViewInit(){
this.renderer.setElementStyle(this.elRef.nativeElement, 'background-image', "url(./assets/imgs/spur-2.jpg)");
}
}