使用javascript文字时不应用Angular类

问题描述

当在模板文字中添加一个类时,它不会更改元素的样式:

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提供的样式规则,然后将新的主机元素属性添加到所有选择器。

enter image description here

因此您可以将组件封装设置为无

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss'],encapsulation:ViewEncapsulation.None
})

或将类添加到全局样式文件中,以便该类将影响项目中具有该类的任何元素

style.scss

.testt {
    color: red;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...