2016-07-14 147 views
9

我正在使用ASP.Net來渲染我的Angular 2應用程序,我唯一的RAZOR頁面是_Layout.cshtml,我希望能夠將一些初始化數據從RAZOR傳遞到我的引導組件,但它不會似乎沒有用。是否可以在Angular 2中將@Input值傳遞給app.component?

在我_Layout.cshtml,我有以下幾點:

<my-app test="abc"></my-app> 

,並在我的app.component.ts,我有:

import { Component, Input } from "@angular/core"; 

@Component({ 
    selector: 'my-app', 
    template: "<div id='mainBody'>Test:{{test}}</div>", 
    directives: [MenuBarComponent, ROUTER_DIRECTIVES] 
}) 
export class AppComponent { 
    @Input() test; 
} 

我的測試變量爲空白。有沒有不同的方式來做到這一點,或者這是不可能的?

+0

http://stackoverflow.com/questions/37337185/passing-asp-net-server-parameters-to-angular-2-app/37384405#37384405 – yurzui

回答

9

不可能爲主要組件(自舉的)使用輸入。您需要直接從DOM獲取屬性:

@Component({ 
    selector: 'my-app', 
    template: "<div id='mainBody'>Test:{{test}}</div>", 
    directives: [MenuBarComponent, ROUTER_DIRECTIVES] 
}) 
export class AppComponent { 
    constructor(private elementRef:ElementRef) { 
    this.test = this.elementRef.nativeElement.getAttribute('test'); 
    } 
} 
+0

如果我想在_Layout中創建一個全局JavaScript對象,我將如何在我的TypeScript構造函數中訪問它? – Scottie

+0

您可以通過[InjectionToken](http://angular.io/guide/dependency-injection-in-action#injectiontok en)將它作爲提供程序添加到您的NgModule中, –

相關問題