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';

  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. 


   <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">
    body {
      margin: 0px;
      padding: 0px;
      background-color: #32435b;
        System.import('app').catch(function(err){ console.error(err); });



The W3C spec states that custom DOM elements should use at least one dash in their names. And when you create Angular components you are essentially creating support for new custom DOM elements. So when you write your selectors for components you want to use dashes between words. And since we are following the style guide on the site, it recommends that selectors get prefixed for your app or feature. Since this is the media watch app let's us a prefix of MW. So if we wanted the app component to be named mw-app, instead of just app, we would set the selector to be mw-app and we would also need to change our DOM element name in the index.html file. And we would set that to the same mw-app.