how to append HTML content in angular 2 using innerHTML
Asked Answered
S

5

10

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">&times;</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.

Saleem answered 30/3, 2017 at 10:58 Comment(4)
What does "and appends it in my component" mean? Never heard of such a thing. Please show your code. See https://mcmap.net/q/53071/-angular-html-binding/…Rarely
Please post your code what you have tried so far.Nonconformance
it sounds like you need to use DomSanitazer, but like @Günter Zöchbauer said - it will be much easier to help if you cound paste some code of yours or plunker...Saltillo
Hey @Saleem this is works fine for me..Nonconformance
M
11

you can directly inject inside your component html.

Plunker link:

https://plnkr.co/edit/lWR6q8?p=preview

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 [innerHTML]="htmlContent"></h2>
    </div>
  `,
})
export class App {
  htmlContent:string;
  constructor() {
    this.htmlContent = `<p>This is my html coontent</p>`
  }
}
Mockingbird answered 10/8, 2017 at 9:18 Comment(1)
If i use ngIf will it work this.htmlContent = '<p ngIf='someVar=true>'This is my html coontent</p>`Pelletier
A
8

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. ☺

Apeman answered 30/3, 2017 at 11:30 Comment(1)
This worked fine for me. But what if I have to do same thing again in the same component? I'm not allowed to use multiple viewchild right? So for the second use, I need to use some other way to append html component. I'm stuck at this point for a while now...Nonplus
K
4
 import { DomSanitizer} from '@angular/platform-browser';
 .... 
 htmlContent:any;
    constructor(private sanitizer: DomSanitizer){
      this.htmlContent = this.sanitizer.bypassSecurityTrustHtml('<p>This is my <strong style="color:red">Paragraph</strong></p>');
}

or you can use a pipe like shown in https://mcmap.net/q/53071/-angular-html-binding

Knurl answered 30/3, 2017 at 11:52 Comment(4)
how can i embed file2.component.html into file1.component.html ?Atrophy
Sorry, I don't understand the question. I'd suggest ti create a new one with more details.Rarely
Ohh sory for that. i will try to explain here, in the above answer we are appending some paragraph<p> . but in my case, that paragraph<p> is there in some other html file. I want to append file2.html content into file1.html. How would i do that ? any suggestionsAtrophy
This question is not about adding files, it's about adding an HTML string. You can use an iframe to show an HTML file.Rarely
J
0

I think the best idea to add html is, to create a directive:

test.directive.ts:

import { Directive,ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Directive({
    selector: '[add-html]'
})

export class TestDirectives{
    constructor(el:ElementRef,private sanitizer:DomSanitizer,private elementRef:ElementRef){
            this.elementRef.nativeElement.innerHTML ='<h1>Hello World</h1>';
    }
}

and now your directive has been created and you will have add this directive into your app.module.ts like below:

app.module.ts:

import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestDirectives } from '../directives/test.directive';


@NgModule({
  declarations: [
    AppComponent,
    TestDirectives
  ],
  imports: [],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You will have to use your directive in your html, where you want to add this html, like in below code:

<div add-html></div>

Now see the output.

Jovia answered 10/8, 2017 at 6:54 Comment(0)
O
0

Create a variable in component.ts file

text:string;
ngOnInit(){
   this.text= "<p>This is new paragraph</p>"
}

And in component.html file add innerHTML attribute like I mentioned below:

<div [innerHTML]="text"></div>

It will append the text value inside the div

<div><p>this is new paragraph</p></div>

I hope it solves your problem :)

Orison answered 17/9, 2020 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.