Is it possible to pass an @Input value to app.comp

2020-03-01 10: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?

回答1:

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