有沒有一種方法來包含一個外部html文件,我一直無法使用templateUrl,它不斷追加基地的URL的開始。angular2包括外部html模板
@Component({
selector: 'enroll-header',
templateUrl: 'http://blank.blank.com/somecool.html'
})
它會嘗試在"./http://blank.blank.com/somecool.html"
找到它並不能
有沒有一種方法來包含一個外部html文件,我一直無法使用templateUrl,它不斷追加基地的URL的開始。angular2包括外部html模板
@Component({
selector: 'enroll-header',
templateUrl: 'http://blank.blank.com/somecool.html'
})
它會嘗試在"./http://blank.blank.com/somecool.html"
找到它並不能
不支持在templateURL中使用外部URL(可能是因爲它使您面臨安全風險)。作爲一種解決方法,您可以在模塊中使用綁定到並顯示單個變量的組件。然後你可以設置變量等於你想渲染的html。請檢查這兩個相似的,所以問題:
我相信所有的templateUrl的是相對於應用程序的根,所以我不認爲這會工作。
最後我用一刮工作得到新的HTML文件,然後addded一個服務器端包含命令在我的索引。 html文件來追加它們。
從'@ angular/core'導入{Directive,ElementRef,Input,OnInit}; 從'@ angular/http'導入{Headers,Http,Response};
@Directive({選擇: 'ngInclude'}) 出口類NgIncludeDirective實現的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() {
this.
http.
get(this.templateUrl).
map(res => this.parseTemplate(res)).
catch(this.handleTempalteError.bind(this)).subscribe(res => {
console.log(res);
});
}
}
你可能會尋找[ComponentFactoryResolver](https://angular.io/ docs/ts/latest/cookbook/dynamic-component-loader.html),其中包含指向plnkr和可下載代碼的鏈接。 – ccpizza