11

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.

In my _Layout.cshtml, I have the following:

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

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?

Scottie
  • 11,050
  • 19
  • 68
  • 109
  • http://stackoverflow.com/questions/37337185/passing-asp-net-server-parameters-to-angular-2-app/37384405#37384405 – yurzui Jul 14 '16 at 20:39

1 Answers1

12

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');
  }
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • If I wanted to create a global javascript object in the _Layout, how would I access that within my TypeScript constructor? – Scottie Jul 14 '16 at 20:37
  • You would add it as a provider in your NgModule via an [InjectionToken](http://angular.io/guide/dependency-injection-in-action#injectiontok‌​en) – Marcelo Mason Jul 20 '17 at 07:06