问题描述
当在模板文字中添加一个类时,它不会更改元素的样式:
comp.html
<div data-js = "tutorial" class ="center main">
</div>
comp.scss
.testt {
color: red;
}
comp.ts
public tutorial: Element;
constructor() { }
ngOnInit() {
this.tutorial = document.querySelector("[data-js='tutorial']");
this.tutorial.innerHTML = `
<h1 class = "testt">
Welcome
</h1>
`;
}
<h1>
的颜色不是红色
解决方法
注入的html不是组件的一部分,因此组件CSS不会影响它。使用
::ng-deep .testt {
color: red;
}
或将CSS添加到全局样式表中
,默认情况下,组件通过以下方式模拟样式的本地作用域:向主机元素添加包含代理ID的属性,并预处理通过styles或styleUrls提供的样式规则,然后将新的主机元素属性添加到所有选择器。
因此您可以将组件封装设置为无
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss'],encapsulation:ViewEncapsulation.None
})
或将类添加到全局样式文件中,以便该类将影响项目中具有该类的任何元素
style.scss
.testt {
color: red;
}