I use innerHTML to render HTML Content in my component. But innerHTML remove all the attributes (eg: removes style attributes) in the HTML content and renders it. But need to render as it is, and doesn't want to extract any attribute from the HTML content. Is there any equivalent to innerHTML or do we can accomplish the desired result with innerHTML. Thanks in Advance.
my template file
<div id="more-info-box" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Title</h4>
</div>
<div class="modal-body">
<div class="clearfix">
<div [innerHTML]="htmlContent" class="long-desc-wrap">
</div>
</div>
</div>
</div>
</div>
</div><!-- End Info box -->
my component file
import { Component } from '@angular/core';
@Component({
selector: 'cr-template-content',
templateUrl: './app/channel.component.html'
})
export class TemplateComponent {
constructor() {
}
htmlContent = '<p>This is my <strong style="color:red">Paragraph</strong></p>'
}
My current output is the content rendered without style attribute. But the desired result should be with style attribute.
to sum up, Angular innerHtml attributes provides dynamic binding of html string content and also using ngAfterViewChecked, we can bind the event listeners Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever.
How html binding works in Angular application. using innerHtml attribute binding, We can bind html content in the form of string. innerHtml attribute can be added to html tag with below two ways. Syntax: <div [innerHTML]="variable"></div> <div innerHTML=" { {variable}}"></div>. Here is a typescript component.
Angular doesn't process HTML added dynamically, it just adds it verbatim except some sanitization to prevent security issues. See In RC.1 some styles can't be added using binding syntax for how to prevent the sanitizer of stripping the HTML.
using innerHtml attribute binding, We can bind html content in the form of string Angular treat innerHtml content as unsafe, so it do sanitize automatically As the raw html content is passed to angular component, We have to check html is trusted or not.
Using ViewChild.
import {ViewChild,ElementRef,Component} from '@angular/core'
create a local variable in the template
<div #div ></div>
query the local variable inside component class
@Component({...}) class MyComponent {
@ViewChild('div') div:ElementRef;
}
access native element inside any function
this.div.nativeElement.innerHTML ="something";
that's it. ☺
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With