簡體   English   中英

在Angular2中操縱DOM的更好方法

[英]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')");
  }
}

另請參閱如何使用ngStyle(angular2)添加背景圖像?

您可以使用模板引用和@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM