gpt4 book ai didi

javascript - 在 Angular2 中操作 DOM 的更好方法

转载 作者:行者123 更新时间:2023-11-29 17:51:35 25 4
gpt4 key购买 nike

与使用 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 中使用绑定(bind)和指令是首选方式,而不是命令式 DOM 操作:

<div [style.background-image]="myService.homeBg"

您需要清理 URL 以便 Angular 接受它。参见 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')");
}
}

另见 How to add background-image using ngStyle (angular2)?

关于javascript - 在 Angular2 中操作 DOM 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com