Sridhar Paiya
Sridhar Paiya

Reputation: 478

Bind HTML code string on Angular 2 template

I have HTML code on Component variable like below :

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `Hi <div [innerHTML]="name"></div>`,
  styleUrls: ['./app.component.css'],
   styles: [`
    .highlight {
      background-color: yellow;
    }
  `],
})
export class AppComponent {
name :string ="dude ! <input type='text'/>";
}

It shows the output like "Hi dude !" But no text box there.How can I display the text box bind using component variable ?

Upvotes: 2

Views: 1472

Answers (1)

Gosha_Fighten
Gosha_Fighten

Reputation: 3858

This code is not secure. So, rendering input elements is disallowed by default. You need to use DomSanitizer to allow it:

constructor(sanitizer: DomSanitizer) {
  this.name = sanitizer.bypassSecurityTrustHtml( this.name);
}

See the plunker sample that illustrates this.

Upvotes: 3

Related Questions