Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate HTML string to real HTML element by ng-for in Angular 2?

Tags:

As I know, in angular 1.x I can use $sce service to meet my requirment like this

myApp.filter('trustAsHTML', ['$sce', function($sce){   return function(text) {     return $sce.trustAsHtml(text);   }; }]); 

and in html file use like this

{{ htmlString || trustAsHTML }} 

Does there has a service like $sce or some pipe or any method can be competent to do that in angularjs 2 version?

like image 932
Garry Avatar asked Nov 02 '15 07:11

Garry


People also ask

How do I display HTML inside an angular binding?

If the HTML value contains a <script> tag, Angular by default will not render it as HTML. If you attempt to render a <script> tag through interpolation ({{ & }}), Angular will render the value as text.

How do I render a string with HTML tag in angular 8?

To render a html string in angular, we can use the innerHTML property by binding a string to it. The innerHTML property sanitizes the html, so that your app is safe from the cross-site scripting attacks(XSS).

Which of the following HTML element is valid in angular template?

Almost all HTML syntax is valid template syntax. However, because an Angular template is part of an overall webpage, and not the entire page, you don't need to include elements such as <html> , <body> , or <base> , and can focus exclusively on the part of the page you are developing.


1 Answers

Simplest solution:

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

Where some_string can be html code, e.g: some_string = "<b>test</b>".

No pipes or anything needed. Supported by Angular 2.0

like image 60
Vingtoft Avatar answered Oct 09 '22 10:10

Vingtoft