This article mainly introduces to you about how to display the content of the CSS style in angular 4, the article through the sample code introduced in very detailed, to everyone's study or work has a certain reference learning value, need to friends below with small to learn together. Before starting the body of this article, let's take a look at the contents of the Angular2 text output on the page, in order to systematically prevent XSS problem, angular all values as untrusted by default. When a value is inserted into the DOM from a template in the form of attributes (property), Dom element attributes (Attribte), CSS class bindings, or interpolation expressions, angular will treat the values harmless (Sanitize) and encode the untrusted values.
H3>binding innerhtml
[innerhtml]= "Htmlsnippet"
This property identifies the HTML tag but does not recognize the value of the attribute in the tag.
Discover problems
Everyone knows that there is a InnerHTML property in angular to set what to display, but if the content contains CSS styles, the effect of the style cannot be displayed.
Like what:
Public content:string = "<p style= ' font-size:30px ' >hello angular</p>"; <p [innerhtml]= "Content" > </p>
Only the Hello world is displayed, the font will not be 30px, that is, the CSS style has no effect.
Solution Solutions
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);}}
Introduction of piping Htmlpipe in the required modules
@NgModule ({declarations: [Htmlpipe]})
Add pipe name in innerHtml
<p [innerhtml]=] content | HTML "></p>
This allows you to display the CSS style of the content.
Related recommendations;
Angular get JSON files defined in the project
What are the Angularjs built-in methods
Introduction to completing form validation with ANGULARJS