Skip to content

Instantly share code, notes, and snippets.

@hG3n
Last active February 27, 2018 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hG3n/7e456123e8f5910cb871d49d563c0081 to your computer and use it in GitHub Desktop.
Save hG3n/7e456123e8f5910cb871d49d563c0081 to your computer and use it in GitHub Desktop.
directive to include an external html file into an existing dom-element
import {Directive, ElementRef, Input, OnChanges, OnInit} from '@angular/core';
import 'rxjs/add/operator/map';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
@Directive({
selector: '[includeHtml]'
})
export class IncludeHtmlDirective implements OnInit, OnChanges {
@Input('includeHtml') filename: string;
private http: HttpClient;
private element_ref: ElementRef;
/**
* c'tor
* @param {Http} http
* @param {ElementRef} el
* usage: <div [includeHtml]="filename"></div>
*/
constructor(http: HttpClient, el: ElementRef) {
this.http = http;
this.element_ref = el;
}
/**
* on init hook initialize
*/
ngOnInit() {
this.initialize();
}
/**
* reinitialize on change
*/
ngOnChanges() {
this.initialize();
}
/**
* init function
* request the file and handle the request
*/
private initialize(): void {
const request = this.http.get(this.filename, {responseType: "text"})
.subscribe(data => {
this.element_ref.nativeElement.innerHTML = data;
}, (error: HttpErrorResponse) => {
console.log(error);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment