Angular 2 - Component selector
Angular will use the selector property from
the component metadata to find a match in the DOM based on an element
name. If we take a look at the app component, we can see that it has
a selector with a value of 'app'. And if we flip over to our index.html file, we can see that
we have a DOM element named
app.
As we learned in an earlier lesson Angular
kicks off with the bootstrap call that takes in an Angular root
module. And the root module has a bootstrap metadata property that
contains a list of components to use as the starting component.
This bootstrap process tells Angular to
look over the initial DOM on the page, take the selector from the app
component and find the first match.
import { Component } from
'@angular/core';
@Component({
selector:
'app',
template:
'<h1>My App</h1>'
})
export class AppComponent
{}
Angular finds the app element and applies
the app component to that element. The bootstrap function will only load
the component on the first match it finds. It will not bootstrap
multiple instances of the same component type. Now this is a bit
different from how components nested in components work. This will get covered
in and upcoming lesson. OK, the app component selector is named app, but
what if you wanted to be more descriptive with it and give it a multi-word
name.
<html>
<head>
<title>Tutespace – Angular2 Tutorials</title>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1">
<script
src="node_modules/core-js/client/shim.min.js"></script>
<script
src="node_modules/zone.js/dist/zone.js"></script>
<script
src="node_modules/reflect-metadata/Reflect.js"></script>
<script
src="node_modules/systemjs/dist/system.src.js"></script>
<script
src="systemjs.config.js"></script>
<link
href="resets.css" rel="stylesheet">
<style>
body {
margin: 0px;
padding: 0px;
background-color: #32435b;
}
</style>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<app>Loading...</app>
</body>
</html>