angular / angular.io

Website for the Angular project (see github.com/angular/angular for the project repo)
https://angular.io
MIT License
1.03k stars 880 forks source link

Cookbook idea: show how to pass info into a root component from host page #1871

Open wardbell opened 8 years ago

wardbell commented 8 years ago

Many apps would like to pass information from the host web page to the Angular app on the page. That A2 app is the root component.

The desired information is typically generated into the web page by a server-side rendering engine, e.g., rendering in a Node Express app, razor output in an ASP.NET MVC app.

This is a documentation request, derived from angular issue #1858.

The following describes much of what this cookbook would demonstrate.

There are at least three ways info could arrive:

  1. as an attribute value generated into the app root element attribute: <my-app name="John Doe"></my-app>
  2. as data generated into the page as a JavaScript/JSON value accessible from window.document
  3. as values generated into the HTML (visible or invisible) within a well-known tag, in a manner the app can interpret.

    1. Attribute value case

A root component can't bind to inputs because it sits above all other components; there is no parent component to bind to. So we can't treat name="John Doe" as an input property binding. Per angular issue #1858, we can inject elementRef and get the attribute value from there.

2. JavaScript data case

Can create a service to access data in window.document and provide that service during bootstrapping. See Rob's example in angular issue #1858.

3. Data-in-page case

The solution is a variation on (2) in which the service extracts the in-page data as innerHtml and turns it into data for the app to consume.

manklu commented 7 years ago

You could inject something at bootstrap.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule }     from './app.module';
import { AppConfig }     from "./app.config";
import { AppConfigImpl } from "./app.config-impl";

{
    var config       = new AppConfigImpl();
    config.title     = "Tour of Heroes";
    config.heroesUrl = "app/heroes";

    platformBrowserDynamic([{provide: AppConfig, useValue: config}])
        .bootstrapModule(AppModule);
}