html input textbox tag stored in a variable show it in angular template

Viewed 1462

I have a variable that is assigned HTML text box tag.i want to display as text box and access its value

@Component({
  selector: 'app-field-add',
  templateUrl: './field-add.component.html',
  styleUrls: ['./field-add.component.css']
})
export class FieldAddComponent implements OnInit 
{
    public htmlTextBox ="<input type='text' [(ngModel)]='Field'  name='Field'>"
}

On The template I have placed the variable

{{ htmlTextBox }}
3 Answers

That is the way that you would display plain text in your div, like so

Solution 1:

<div class="blog-post">{{testhtml}}</div>

But that will write out text, not HTML.

For HTML, you will need to bind to the property

Solution 2:

<div class="blog-post" [innerHtml]="testhtml"></div>

Leaving out the square brackets would bind to the attribute, so you would need to interpolate again

Solution 3:

<div class="blog-post" innerHtml="{{testhtml}}"></div>

The property binding (Solution 2) is the preferred method.

Angular security Blocks dynamic rendering of HTML and other scripts. You need to bypass them using DOM Sanitizer.

DO below changes in your code :

// in your component.ts file

//import this 
import { DomSanitizer } from '@angular/platform-browser';


// in constructor create object 

constructor( 
...
private sanitizer: DomSanitizer

...
){

}

someMethod(){
 let htmlTextBox ="<input type='text' [(ngModel)]='Field'  name='Field'>"
 this.htmlData = this.sanitizer.bypassSecurityTrustHtml(htmlTextBox ); // this line bypasses angular security

}

and in HTML file ;

<!-- In Your html file-->
    <div [innerHtml]="htmlData">
    </div>

You can read more here : Angular security

Working example : Working stackblitz

Try innerHtml:

<div [innerHtml]="htmlTextBox">
</div>
Related