Ahmedul Haque Abid Ahmedul Haque Abid - 3 months ago 25
TypeScript Question

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

Answer

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

Comments