2017-02-14 64 views
1

有沒有一種方法來包含一個外部html文件,我一直無法使用templateUrl,它不斷追加基地的URL的開始。angular2包括外部html模板

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

它會嘗試在"./http://blank.blank.com/somecool.html"

找到它並不能

+0

你可能會尋找[ComponentFactoryResolver](https://angular.io/ docs/ts/latest/cookbook/dynamic-component-loader.html),其中包含指向plnkr和可下載代碼的鏈接。 – ccpizza

回答

2

我相信所有的templateUrl的是相對於應用程序的根,所以我不認爲這會工作。

0

最後我用一刮工作得到新的HTML文件,然後addded一個服務器端包含命令在我的索引。 html文件來追加它們。

0

從'@ 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); 
     }); 
} 

}