Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass an @Input value to app.component in Angular 2?

Tags:

angular

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?

like image 570
Scottie Avatar asked Jul 14 '16 19:07

Scottie


People also ask

How do you pass data into App components?

Firstly, we have to create a custom property to pass the data into a component. This can be done via input binding, which passes data from one component to another, generally from parent to child. This custom input binding is created by using the @Input() decorator.

When and where @input Decoratator can be used in a component?

@Input Decorator. @Input is a decorator to mark a property as an input. @Input is used to define an input property, to achieve component property binding. @Inoput decorator is used to pass data (property binding) from parent to child component.

How do you pass value from component to component?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.


1 Answers

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');
  }
}
like image 179
Thierry Templier Avatar answered Sep 19 '22 17:09

Thierry Templier