Forward Advance Learning

Nesting Components

Angular 2 is built out of components. Up till now, our applications have consisted of a single component, but a real app will be made out of a tree of components, one inside the next.

Because child components are injected into their parent, order of definition matters. We get around this using a module loader, more on this later, but for now we're going to continue putting everything in one file.

A Cat Component

Let's create a component that can sit on our page. I'm going to make a Cat Component to render out a single cat.

Because we have no module loader, we must define the child component first in our source.

var CatComponent = ng.core
.Component({
selector: 'cat',
template: '<h1>Here is {{catName}} the cat!</h1>'
})
.Class({
constructor: function() {
this.catName = "Fluffy"
}
});

Now for the app component

Next we define the parent component, which will be the root of the tree:

var AppComponent = ng.core
.Component({
selector: 'app',
template: '<cat></cat>'
})
.Class({
constructor: function() {}
});

Finally we can bootstrap:

ng.platformBrowserDynamic
.platformBrowserDynamic()
.bootstrapModule(AppModule);

Simple Exercise - A little web app

Create a little page with header, footer and main components, so your app template looks like this:

<header></header>
<main></main>
<footer></footer>

You will need to create each component separately, and add them to the module.

Later we will look at passing data into our component and sending it back out again.

Escape the Dungeon Exercise - Split into components

Your game renders a location and a hero. Break these into separate components, so you have a <protagonist> component and a <location> component.