I create an Angular project and I wanted to insert style
CSS into the html, but I don't want the inserted CSS replace other style that have the same tag or class name.
const testStyle = '<style>
body {color: red}
table {width : 200px}
h1{font-size:12px}
.another-same-class-name{color: blue;font-size: 13px}
</style>'
Above is my sample style that I want to insert into my component template
My Component
@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>
Edit: I have update my question, to make it more clear :)
I appreciate any kind of solution.
First, select the element by running the DOM method document. querySelector(). You can also set the types of styles for the selected element via style.
Angular 2+ supports an [innerHTML] property binding that will render HTML. If you were to otherwise use interpolation, it would be treated as a string. In this article, you will be presented with how to use [innerHTML] and some considerations for usage.
Use the document. createElement() method to create the style tag. Use the textContent property to assign styles to the tag. Add the style tag to the head using the appendChild() method.
Both APIs ::ng-deep and /deep/ are deprecated and will eventually be removed in the future.
You need to use DomSanitizer of @angular/platform-browser
to sanitize the HTML.
Take a look of the docs: https://angular.io/api/platform-browser/DomSanitizer.
In your particular case, you need to use bypassSecurityTrustHtml()
method. Also, for apply styles only to one component, add an id
to your target component and use it in your styles. (You can use class if that component will appear more than once in your web).
EXAMPLE:
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>`);
}
}
DEMO: https://stackblitz.com/edit/angular-3kza7c?file=src%2Fapp%2Fapp.component.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With