简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM