我正在研究Angular 2中的LoginComponent
应该“重新设置”html
和body
标签,因此我可以放入特定于登录页面的背景图像。
但只是在我的html, body
中为login.css
添加样式似乎不起作用。
有没有办法从组件覆盖html, body
上的样式?或任何元素。
我尝试过这样的事情:
:host(.btn) { ... }
:host(.btn:host) { ... }
.btn:host { ... }
从Login
组件外部设置元素的样式。但似乎没有任何效果。
你可以试试
body {
/* body styles here */
}
但组件中的样式不应该应用于自身之外的元素。
另一种方法是在主要组件中使用body
作为选择器,并使用host-binding设置/删除body上的CSS类,以使您添加到index.html匹配的CSS。
@Component({
selector: "body",
host: {
"[class.some-class]":"someClass"
},
})
export class AppComponent {
constructor(private loginService: LoginService) {
loginService.isLoggedInChanged.subscribe((value) => {
this.someClass = value;
});
}
someClass: bool = false;
}
当您将someclass
设置为true时(使用某些绑定到服务,该类将添加到正文中)。
如果您不想全局添加CSS,也可以直接绑定到样式属性
@Component({
selector: "body",
host: {
"[style.background-image]":"bodyBackgroundImage()"
},
})
export class AppComponent {
bool isLoggedIn = false;
constructor(private loginService: LoginService) {
loginService.isLoggedInChanged.subscribe((value) => {
this.isLoggedIn = value;
});
}
function bodyBackgroundImage() {
return this.isLoggedIn ? 'url("gradient_bg.png")': 'none';
}
}
更新
DomAdapter
走了。 Renderer2应该提供类似的功能。
直接从登录组件设置<body>
样式的方法是使用DomAdapter
(另请参阅https://github.com/angular/angular/issues/4942)
System.import('angular2/src/platform/browser/browser_adapter').then(function(browser_adapter) {
browser_adapter.BrowserDomAdapter.makeCurrent();
})
...
_dom: DomAdapter = new BrowserDomAdapter();
_dom.setStyle(_dom.query('body'), 'padding', '50px');
您需要使用ViewEncapsulation更改组件为css提供服务的方式。默认情况下,它设置为Emulated
和angular will
添加包含代理项ID的属性并预处理样式规则
要更改此行为import ViewEncapsulation from 'angular2/core'
并在组件的元数据中使用它:
@Component({
...
encapsulation: ViewEncapsulation.None,
...
})
我不确定这是否正是您正在寻找的,但这不会让您永久改变身体背景图像。
这是我为类似的东西做的。如果你想影响这个页面的身体背景图像,这可能会有效。 (我没有完全测试过,但它似乎适用于Windows浏览器。)
在组件内部,您可以在构建组件时直接通过DOM工作。当它被破坏时,您可以撤消更改。
export class SpecialBackground {
constructor(){
document.body.style.backgroundImage = "url('path/to/your/image.jpg')";
document.body.style.backgroundPosition = "center center";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundAttachment = "fixed";
document.body.style.backgroundSize = "cover";
}
ngOnDestroy(){
document.body.style.backgroundImage = "none";
}
}
为了您的目的,当您单击按钮时,您可以使用不同的功能(而不是构造函数),您应该好好去。
我用它的方式是
constructor() {
document.body.className = "bg-gradient";
}
ngOnDestroy(){
document.body.className="";
}
这将为特定组件动态添加和删除正文的样式。
我刚刚编辑了styles.scss文件,它对我有用。
我有与margin-top相同的问题,我修复的方式是
constructor(
private _renderer: Renderer2,
) {
this._renderer.removeStyle(document.body, 'margin-top');
}
这对我很有用。
我在我的组件中使用这种方法,在路由器插座中加载:
ngOnInit() {
// Change <body> styling
document.body.classList.add('align-content-between');
}
ngOnDestroy() {
// Change <body> styling
document.body.classList.remove('align-content-between');
}
最好在根级别添加css文件并在angular-cli.json中配置它或在index.html中添加它。所以你可以编写你的重置和全局样式,而不必担心影子和其他概念。