Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from html body to root component

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

like image 566
Ahmedul Haque Abid Avatar asked Aug 09 '16 05:08

Ahmedul Haque Abid


3 Answers

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

like image 39
Ratnam Alubelli Avatar answered Oct 25 '22 04:10

Ratnam Alubelli


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);
}
like image 135
John Pankowicz Avatar answered Oct 25 '22 03:10

John Pankowicz


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:

  • Angular 2 input parameters on root directive

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...

like image 40
Thierry Templier Avatar answered Oct 25 '22 04:10

Thierry Templier