javascript - Angular将样式标签添加到innerHTML
问题描述
我创建了一个 Angular 项目,我想将style
CSS 插入到 html 中,但我不希望插入的 CSS 替换具有相同标签或类名的其他样式。
const testStyle = '<style>
body {color: red}
table {width : 200px}
h1{font-size:12px}
.another-same-class-name{color: blue;font-size: 13px}
</style>'
以上是我想插入到我的组件模板中的示例样式
我的组件
@Component({
selector : 'app-my-component',
templateUrl: './my-template.component.html',
styleUrls: ['./my-style.component.scss'],
})
export class MyComponent{
myStyle:string
...
ngOnInit(){
const testStyle = '<style>
body {color: red}
table {width : 200px}
h1{font-size:12px}
.another-same-class-name{color: blue;font-size: 13px}
</style>'
this.myStyle = testStyle
}
updateCss(newCss){
this.myStyle = `<style>${newCss}</style>`
}
}
<div #styleWillGoHere [innerHtml]="myStyle"></div>
编辑:我已经更新了我的问题,让它更清楚:)
我很欣赏任何一种解决方案。
解决方案
您需要使用 DomSanitizer@angular/platform-browser
来清理 HTML。
查看文档:https ://angular.io/api/platform-browser/DomSanitizer 。
在您的特定情况下,您需要使用bypassSecurityTrustHtml()
方法。此外,对于仅将样式应用于一个组件,将一个添加id
到您的目标组件并在您的样式中使用它。(如果该组件在您的网络中出现多次,您可以使用类)。
例子:
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div id="myId">
<div [innerHtml]="myStyle"></div>
<h1>Hello</h1>
</div>
`
})
export class AppComponent {
myStyle: SafeHtml;
constructor(private _sanitizer: DomSanitizer) { }
ngOnInit() {
this.myStyle =
this._sanitizer.bypassSecurityTrustHtml(`<style>#myId h1{color: red}</style>`);
}
}
演示: https ://stackblitz.com/edit/angular-3kza7c?file=src%2Fapp%2Fapp.component.ts
推荐阅读
- firebase - 如何在颤动中模糊网络图像
- webpack - webpack 给我错误“@font-face { ^ 意外令牌”
- tags - 使用 Zebra RFD8500 读取 Dogbone (Magnus 3) 传感器标签
- r - 在 R 中将列名作为变量传递的问题
- laravel - Laravel 中的 Vue 表单组件在提交时收到 422 错误
- java - Keycloak-Admin-Client in a JPMS/Jigsaw Java 11 Maven application - Dependency Problems
- javascript - React Native websocket event.data接收二进制数据时为空数组
- javascript - PHP 适用于 Localhost 但不适用于服务器
- linux - Divide words in one column to three equal columns using Linux terminal
- maven - 从另一个 Mojo 以编程方式触发 Mojo