[英]Better way of manipulating the DOM in Angular2
與使用document.getElementById('id').style.backgroundImage
相比,操縱DOM
更改特定div背景的更好方法是什么?
我嘗試在更改Url時更改背景,但是我能想到和輕松實現的唯一方法是使用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();
}
在Angular2中,首選使用綁定和指令,而不是命令式DOM操作:
<div [style.background-image]="myService.homeBg"
您需要清理Angular的URL才能接受它。 有關更多詳細信息,請參見RC.1中的某些樣式無法使用綁定語法添加 。
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')");
}
}
您可以使用模板引用和@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)");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.