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?
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.
@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.
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.
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With