2

I have a component with onClick function that returns HTML code with angular component and I want to show it on a template. How can I do it?

Because in a current state I am getting just "Test code", without democomponent.

export class AppComponent {
  title = 'app';

  content;

  onClick(){
    console.log("Clicked!")
    this.content = "Test code <democomponent></democomponent>";
  }
}

 <div>
  <button (click)="onClick()">Click</button>
<div>
  <div [innerHtml]="content"></div>
</div>
</div>
  • To make it short: you can't. It would need to compile the HTML, and the whole point of AOT compolation in Angular is to avoid shipping the compiler. Find another way to solve the actual problem you're trying to solve. – JB Nizet Jun 24 '18 at 19:19
  • Have a look at [this](https://stackoverflow.com/a/38472185/5695162) – Vikas Jun 24 '18 at 19:32

1 Answers1

1

This may not be the 'cleanest' approach though it runs in Angular 6.

First I created a component called dummy.ts, [you can call it any name you want...] using following ng command

ng generate component dummy

Before adding anything in dummy.ts component content, I first needed to define a pipe file. For convenience I generated the pipe in same dummy.ts component folder, using following ng command:

ng generate pipe SafeHtml

I then added the following code:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
 name: 'safeHtml'
})

export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitized: DomSanitizer) {}

  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
}}

Finally back in dummy.ts I added this very simple basic code.

import { Component, OnInit } from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { SafeHtmlPipe } from './safe-html.pipe';

@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.css']
})

export class DummyComponent implements OnInit {
   name:string;
   safeHtmlContent : string;
   dummyContent : string;

   onClick(){
     this.safeHtmlContent  = this.dummyContent;
   }

  constructor() {
    this.dummyContent  = '<h4>Some dummy title</h4><p>Some blah blah blah blah blah... dummy content</p>';
  }}

and in dummy.html I simply added the following:

<div>
 <button (click)="onClick()">Click</button>
</div>

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

As a result when a click on button it displays expected raw HTML enter image description here
Hope this helps ;)

PeteZaria
  • 302
  • 3
  • 9