【问题标题】:Is it possible to pass an @Input value to app.component in Angular 2?是否可以在 Angular 2 中将 @Input 值传递给 app.component?
【发布时间】:2016-11-17 21:12:37
【问题描述】:

我正在使用 ASP.Net 来呈现我的 Angular 2 应用程序,我拥有的唯一 RAZOR 页面是 _Layout.cshtml,我希望能够将一些初始化数据从 RAZOR 传递到我的引导组件中,但是它好像没用。

在我的 _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;
}

我的测试变量是空白的。有没有其他方法可以做到这一点,还是不可能?

【问题讨论】:

标签: angular


【解决方案1】:

不能对主要组件(自举组件)使用输入。您需要直接从 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');
  }
}

【讨论】:

  • 如果我想在 _Layout 中创建一个全局 javascript 对象,我将如何在我的 TypeScript 构造函数中访问它?
  • 你可以通过InjectionToken将它作为提供者添加到你的NgModule中
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 2012-09-30
  • 2021-06-30
  • 2021-05-08
  • 2021-12-30
相关资源
最近更新 更多