Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Interpolate string with html

How to Interpolate string with html using angular2. i know in angular 1.x there is $interpolate(templateString)(miniScope); but i haven't find the same for angular2.

suppose i have a template like this : Hello my name is {{name}}

and binding is like name: "<strong>Pardeep</strong>"

so i want result like

Hello my name is Pardeep

Refer for angular1

for angular2 see here but i'm unable to understand clearly

any help ?

like image 252
Pardeep Jain Avatar asked Jul 09 '16 06:07

Pardeep Jain


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).

What is the difference between string interpolation and property binding?

Interpolation is used to just display a piece of data in HTML, such as displaying a title or a name. Property binding lets us bind a property of a DOM object, for example the hidden property, to some data value.

What is string interpolation in Angular with an example?

String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.


1 Answers

You can simply use [innerHTML] directive to accomplish it.

http://plnkr.co/edit/6x04QSKhqbDwPvdsLSL9?p=preview

import {Component, Pipe} from '@angular/core'  @Component({   selector: 'my-app',   template: `             Hello my name is <span [innerHTML]="myName"></span>    `, }) export class AppComponent {    myName='<strong>Pardeep</strong>';  } 

Update:

I checked it doesn't work this way after RC.1 release.

Let's say to make it work with RC.4 you can use DomSanitizationService as shown below,

@Component({   selector: 'my-app',    template: `     <div [innerHTML]="myCheckbox"></div>   `, }) export class AppComponent {    dangerousUrl='<input type="checkbox">';    constructor(sanitizer: DomSanitizationService) {      this.myCheckbox= sanitizer.bypassSecurityTrustHtml(this.dangerousUrl);   } } 

http://plnkr.co/edit/Yexm1Mf8B3FRhNch3EMz?p=preview

like image 108
Nikhil Shah Avatar answered Oct 07 '22 22:10

Nikhil Shah