在开发Login模块时。我在html中有一个主题构建,我需要将其集成到我的登录模块中。 现在它需要html的主体包含一个自定义的css(login.page.css)。 一种方法是将自定义css添加到index.html主体中,但之后该css将应用于我将来甚至不需要它的每个页面。所以我厌倦了下面的代码......
//FileName: login.component.ts
@Component({
selector: 'login-app' ,
templateUrl: './login.component.html',
styleUrls: ['./login.page.css', './login.component.css']
})
export class LoginComponent implements OnInit {
ngOnInit(){
let body = document.getElementsByTagName('body')[0];
//body.classList.add("theme-default"); //add the class
body.classList.add("page-signin"); //add the class
}
它成功地将css添加到身体但它未能改变身体的风格。
*固定
使用ViewEncapsulation来实现这一目标......
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'login-app' ,
templateUrl: './login.component.html',
styleUrls: ['./login.page.css', './login.component.css'],
encapsulation: ViewEncapsulation.None
})
export class LoginComponent implements OnInit {
ngOnInit(){
let body = document.getElementsByTagName('body')[0];
//body.classList.add("theme-default"); //add the class
body.classList.add("page-signin"); //add the class
}
}
在这段代码中,ngOnInit函数和几个js代码用于将我的css推入正文。但是这不会将login.page.css渲染到DOM中,而是将在shadow DOM中渲染,因此这种css样式将仅用于当前模块而不是主体。为了在@Component中使用代码
encapsulation: ViewEncapsulation.None
这将允许我的CSS也渲染主要的dom元素。我会感谢你们更好的解决方案,但如果没有任何效果。试试这段代码吧!