Home >Web Front-end >JS Tutorial >Sample code to display CSS styles in Angular4
This article mainly introduces to you the relevant information about the CSS style of how to display content in Angular 4. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it can follow Let’s learn together with the editor. Hope it helps everyone.
Preface
Before starting the main text of this article, let’s first take a look at the related content of outputting tagged text on the page in angular2. In order to systematically prevent XSS issues, Angular defaults to Treat all values as untrusted. When values are inserted into the DOM from the template through attributes (Property), DOM element attributes (Attribte), CSS class bindings, or interpolation expressions, Angular will sanitize these values (Sanitize). Untrusted values are encoded.
h3>Binding innerHTML</h3> <p>Bound value:</p> <p class="e2e-inner-html-interpolated">{{htmlSnippet}}</p> <p>Result of binding to innerHTML:</p> <p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
[innerHTML]="htmlSnippet"
This attribute can identify the HTML tag but not the attribute value in the tag
Found the problem
Everyone knows that there is the innerHTML attribute in Angular to set the content to be displayed. However, if the content contains CSS styles, the effect of the styles cannot be displayed.
For example:
public content: string = "<p style='font-size:30px'>Hello Angular</p>"; <p [innerHTML]="content"></p>
Only Hello World will be displayed, and the font will not be 30px, that is, the CSS style will have no effect.
Solution
Customize a Pipe to convert the content. Look at the code below.
Write a HtmlPipe class
import {Pipe, PipeTransform} from "@angular/core"; import {DomSanitizer} from "@angular/platform-browser"; @Pipe({ name: "html" }) export class HtmlPipe implements PipeTransform{ constructor (private sanitizer: DomSanitizer) { } transform(style) { return this.sanitizer.bypassSecurityTrustHtml(style); } }
Introduce the pipe HtmlPipe into the required module
@NgModule({ declarations: [ HtmlPipe ] })
Add the pipe name to innerHtml
<p [innerHTML]="content | html"></p>
so that the content can be displayed CSS styles.
Related recommendations:
Detailed explanation of the implementation method of a complete Angular4 FormText component
Angular4 form response function example analysis
Project preparation and environment building operations in Angular4
The above is the detailed content of Sample code to display CSS styles in Angular4. For more information, please follow other related articles on the PHP Chinese website!