2016-07-14 151 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中, –

相关问题