I've been trying to pass data from main layout index.html file to the angular root/starting component <my-app>
. Unfortunately I'm unable to pass them like this: <my-app [bodyData]="'passed'" ></my-app>
from my index.html.
Can anyone help me how can I pass them? Provided a test link.
Plunker Test App Link
I have tried same scenario. But I am getting the value as null.
In my HTML I have the tag
<my-app myattr="passed" >Loading ..</my-app>
And in the component I have used
constructor(private _elementRef: ElementRef){
let native = this._elementRef.nativeElement;
let test = native.getAttribute("myattr");
alert(test);
}
That alert value is coming as null
As @Thierry states above, his proposed method is only valid for passing string attributes. Below is a method by which you can pass in an object with defined properties.
Create a class for the data you want to pass.
appdata.ts
export class AppData {
public isServerRunning: boolean;
public isDataFromMemory: boolean;
}
Define an instance on the window object containing your startup data
index.html
<script>window.APP_DATA = { isServerRunning: false, isDataFromMemory: false }
Tell the bootstrap code about it.
main.tss
import { AppData } from './app/appdata';
Provide the data via a service to your components
app.module.ts
import { AppData } from './appdata';
...
providers: [AppData,
{
provide: AppData,
useValue: window['APP_DATA']
}
],
Access the data from a component
app.component.ts
constructor(appData:AppData) {
console.log('AppComponent - ', appData);
}
Property binding doesn't work on the root components, i.e. the components you bootstrap.
The reason why this is not working is that your index.html in which you place the is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise, we would get a performance hit. (Tobias Bosch)
See this question:
A workaround would be to leverage the DOM:
<my-app bodyData="passed" ></my-app>
and in the component:
@Component({
selector: 'my-app',
template: `
(...)
`
})
export class MyAppComponent {
constructor(private eltRef:ElementRef) {
let prop = eltRef.getAttribute('bodyData');
}
}
This will only work for string attributes...
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