Keeping up the tradition, before we start building a real application together, we should write our first hello world component with Angular:
import {Component} from '@angular/core';
@Component({
selector: 'hello-world',
template: '<div>Hello {{name}}</div>'
})
class HelloWorldComponent {
name: string = 'World';
}
This is already a fully-working Angular component. We used ECMAScript 6 classes to create the necessary encapsulation required for a component. You can also see a meta-annotation that is used to declaratively configure our component. This statement, which looks like a function call that is prefixed with an at symbol, actually comes from the ECMAScript 7 decorator proposal. For the moment, you can think of decorators as a way to attach metadata to our component class.
It's important to understand that an element can only be bound to one single component. As a component always comes with a view, there is no way that we can bind more than one component to an element. On the other hand, an element can be bound to many directives, as directives don't come with a view—they only attach behavior.
In the Component decorator, we need to configure everything that is relevant to describe our component for Angular. This, of course, also includes our template for the view. In the preceding example, we are specifying our template directly within JavaScript as a string. We can also use the templateUrl property to specify a URL where the template should be loaded from.
The second configuration, applied using the selector property, allows us to specify a CSS selector, which is used by Angular to attach the component to certain elements within our view. Every time Angular encounters an element which matches the component's selector, it will render the given component into that element.
Now, let's enhance our example a little bit so that we can see how we can compose our application from smaller components:
import {Component} from '@angular/core';
@Component({
selector: 'shout-out',
template: '<strong>{{words}}</strong>'
})
class ShoutOutComponent {
@Input() words: string;
}
@Component({
selector: 'hello-world'
template: '<shout-out words="Hello, {{name}}!"></shout-out>'
})
class HelloWorldComponent {
name: string = 'World';
}
You can see that we have now created a small component that allows us to shout out words as we like. In our Hello World application, we make use of this component to shout out Hello, World!
Within the template of our hello world component, we are including the shouting component by placing an HTML element which matches the CSS element selector of the shouting component.
Over the course of this book and while writing our task management application, we will learn a lot more about the configuration and implementation of components. However, before we start with this in the Chapter 2, Ready, Set, Go!, we should take a look at some tools and language features that we'll use during this book.