是否可以在Angular 2中将@Input值传递给app.component? [英] Is it possible to pass an @Input value to app.component in Angular 2?

查看:70
本文介绍了是否可以在Angular 2中将@Input值传递给app.component?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.Net渲染Angular 2应用,而我拥有的唯一RAZOR页面是_Layout.cshtml,我希望能够将一些初始化数据从RAZOR传递到我的自举组件中,但是似乎不起作用.

I'm using ASP.Net to render my Angular 2 app, and the only RAZOR page I have is the _Layout.cshtml and I would love to be able to pass some init data from RAZOR into my bootstrapped component, but it doesn't seem to work.

在_Layout.cshtml中,我有以下内容:

In my _Layout.cshtml, I have the following:

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

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

and in my app.component.ts, I have:

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;
}

我的测试变量为空.有其他方法可以做到吗?还是不可能?

My test variable is blank. Is there a different way to do this, or is it just not possible?

推荐答案

无法对主要组件(自举组件)使用输入.您需要直接从DOM获取属性:

It's not possible to use inputs for main components (bootstrapped ones). You need to get the attribute directly from the 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');
  }
}

这篇关于是否可以在Angular 2中将@Input值传递给app.component?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆