2

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 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Try innerHtml:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.