2017-04-26 65 views
1

我想從一個JSON文件中提取一個值來設置一個模板URL。該值將成爲Angular獲取模板內容的URL。基本上,我想拿出某種形式的解決方案,使得所需的HTML模板可以由用戶在後臺設置,和我的角度服務發出請求到S3,這臺templateUrl.Angular 2 - 從變量設置templateUrl?

import { Component, OnInit } from '@angular/core'; 
import { GlobalDirective } from '../../global.directive'; 

@Component({ 
selector: 'terms-form', 

//need to be able to specify this templateUrl as a variable from the JSON sitting on S3. 

templateUrl: URL value from JSON, 
styleUrls: ['./terms.component.css'] 
}) 

export class TermsFormComponent implements OnInit { 

constructor(public globalDirective: GlobalDirective) {} 


ngOnInit() { 
    this.globalDirective.getData(); 

} }

我在這裏發現了一些類似的問題,但沒有爲我的問題工作。我正在使用@angular/cli: 1.0.1

+2

請問此處的信息幫助 在我的情況IM:https://angular.io/docs/ TS /最新/菜譜/動態組件loader.html – DeborahK

回答

1

我認爲你不能這樣做,但你總是可以注入一個模板。

@Component({ 
    selector: 'my-cmp', 
    template: ` 
     <ng-container [ngTemplateOutlet]="template" [ngOutletContext]="{name: name}"></ng-container> 
    `, 
}) 
export class MyCmp { 
    @Input() template: TemplateRef<any>; 
    @Input() name: string; 

    constructor() { 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <my-cmp [template]="one" [name]="'julia'"></my-cmp> 
    <my-cmp [template]="two" [name]="'kate'"></my-cmp> 

    <ng-template #one><div>here is a template one {{name}}</div></ng-template> 
    <ng-template #two><div>here is a template two {{name}}</div></ng-template> 
    `, 
}) 
export class App { 
    @ViewChild('one', { read: TemplateRef }) one: TemplateRef<any>; 
    @ViewChild('two', { read: TemplateRef }) two: TemplateRef<any>; 

    constructor() { 
    } 
} 
0

嘿它已經有一段時間,但嘗試這個辦法:用我的環境文件提供的依賴

//This is the only way to use resource files dependency injection (expect for using template): 
//encapsulating the environment variable in another variable prevents it from being undefined inside @component 
//using "" + the variable prevents Error: Cannot find module "." at webpackMissingModule 
var tmp = environment; 
@Component({ 
    selector: 'my-selector', 
    templateUrl: "" + tmp.html, 
    styleUrls: ["" + tmp.css] 
})