rich green
rich green

Reputation: 1213

angular2 include external html template

Is there a way to include an external html file, I've been unable to use templateUrl, it keeps appending the base to the start of the url.

@Component({
  selector: 'enroll-header',
  templateUrl: 'http://blank.blank.com/somecool.html'
})

it'll try to find it at "./http://blank.blank.com/somecool.html"

and fail

Upvotes: 2

Views: 35477

Answers (4)

Akshay Bohra
Akshay Bohra

Reputation: 319

import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

@Directive({ selector: 'ngInclude' })
export class NgIncludeDirective implements OnInit {

@Input('src')
private templateUrl: string;
@Input('type')
private type: string;

constructor(private element: ElementRef, private http: Http) {

}
parseTemplate(res: Response) {
    if (this.type == 'template') {
        this.element.nativeElement.innerHTML = res.text();
    } else if (this.type == 'style') {
        var head = document.head || document.getElementsByTagName('head')[0];
        var style = document.createElement('style');
        style.type = 'text/css';
        style.appendChild(document.createTextNode(res.text()));
        head.appendChild(style);
    }
}
handleTempalteError(err) {

}
ngOnInit() {
    //Loads the HTML and bind it to the view
    this.
        http.
        get(this.templateUrl).
        map(res => this.parseTemplate(res)).
        catch(this.handleTempalteError.bind(this)).subscribe(res => {
            console.log(res);
        });
}

}

Upvotes: -1

rich green
rich green

Reputation: 1213

I ended up using a scrape job to get the new html files, and then addded a serverside include command in my index.html file to append them.

Upvotes: 0

Jim
Jim

Reputation: 4192

Using an external URL in templateURL is not supported (possibly because it exposes you to security risks). As a workaround you can use a template with your component that binds to and displays a single variable. Then you can set the variable equal to the html you want to render. Please check these two similar SO questions:

Upvotes: 3

chrispy
chrispy

Reputation: 3612

I believe all of the templateUrl are relative to the root of your application, so I don't think this would work.

Upvotes: 2

Related Questions