Angular – How to display an HTML fragment inside the component’s template

Angular

Angular has built-in protections against common web-application vulnerabilities and attacks such as cross-site scripting attacks.

Angular’s cross-site scripting security model

To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template binding, or interpolation, Angular sanitizes and escapes untrusted values.

Solution

Angular 2+ supports an [innerHTML] property binding that will render HTML. 

Example #1

Snippet for component.ts.

htmlFragment = "<span>Products Explorer</span>";

Snippet for component.html.

<div [innerHTML]="htmlFragment"></div>

Example #2

Snippet for component.ts.

htmlFragments = [ "<span>Products Explorer</span>", "<span>M.T.J. Music</span>" ];

Snippet for component.html.


<div *ngFor="let item of htmlFragments" [innerHTML]="item"></div>
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená.