Saturday, January 11, 2020

Load Dynamic Html in Div using Angular

Hi Guys ,

In this blog we will discuss on how to load a dynamic HTML into a div .
Lets assume the source of the HTML is a service .
In angular , you can perform this using a user defined directive and ng-template .

Let us first create a custom directive .

import { Directive , ElementRef,Inputfrom '@angular/core';

@Directive({
  selector: '[appContent]'
})
export class ContentDirective {
  @Input()  innerHtml ;
  constructor(private elElementRef) { }
  
  ngOnInit() {
    this.el.nativeElement.innerHTML = this.innerHtml;
    console.log(this.innerHtml);
   }


   ngAfterContentInit(){
    console.log(this.innerHtml);
   }

   ngAfterViewInit(){
    console.log(this.innerHtml);
   }
}


Now , let us create a service to fetch the response HTML .

import { Injectable } from "@angular/core";
import { HeadersHttpResponse } from '@angular/http';

@Injectable({
    providedIn: 'root'
  })
export class AppService {

    constructor(private httpHttp ) { }

    loadContent(){
        return this.http
        .get('http://localhost:8990/loadFile/b5510b8d-c766-48bd-808d-54c2e6e6d1c2');
    }
}





The next step is to use the custom directive in the component file using ng-template .

<app-header></app-header>

<ng-template [ngIf]="loadcontent" >
    <div  appContent [innerHtml]="content" >

    </div>
<div>
    Footer
</div>

</ng-template>

Hope this helps .Thanks for reading !



No comments:

Post a Comment

ec2-user@ec2 Permission denied