Follow by Email

Angular 2 - Component metadata


Okay, let's build the first component, the app component, in a file named app.component.ts, inside the app directory. To build an Angular component, you need to use the component decorator on a class. The component decorator comes from the core scope package in Angular. 

So, we can add an import statement for the component decorator from the Angular core scope package. And then we can call the decorator, using the app component syntax with the parentheses. Then, we need to export a class for the component. We will name this class AppComponent. So, the class definition reads as: export class AppComponent, and a pair of curly braces. 

                                        
import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<h1>My App</h1>'
})
export class AppComponent {}



Now, just like the NG module decorator, the component decorator takes in a metadata object, with some known properties, to configure a class you decorate as an angular component. 

To decorate a component, you need to provide two metadata properties at a minimum. Selector, and template, or template url. We will pass in an object literal, inside the component decorator parentheses. And for now, we will set the selector property to the stringed value of app. And the template property to a string with an HTML H1 tag. The selector property is what Angular will use to locate a custom HTML element, and apply the component too.


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