Learning Angular for .NET Developers
上QQ阅读APP看书,第一时间看更新

Decorators and metadata

As you saw in the last section, we define JavaScript plain classes for a component, and we annotate it with some information to inform the Angular framework that this class is a component.

We leverage the Typescript syntax and attach the classes with metadata using the decorator feature. To make a class as a component, we add the @Component decorator, as shown in the following code:

@Component({...})
export class FirstComponent {...}

As you can see, the code snippet shows that the FirstComponent class has been decorated as a component.

Now, let's attach metadata to the FirstComponent class using the decorator syntax:

@Component({ 
selector: 'first-component',
templateUrl: 'app/first.component.html'
})
export class FirstComponent {...}

Here, we have added metadata, such as a selector and templateUrl. The selector metadata configured in the component tells Angular to create the instance of a component when it encounters the <first-controller> markup:

<first-controller></first-controller> 

The templateUrl provides a URL of the template file for the component to render. When you run the application, the <first-controller> tag will be replaced by the content of the template that is referred to in templateUrl. This metadata is actually a parameter to the @Component decorator, and the decorator is a function.

By adding metadata via decorators, we are actually telling Angular what to do with the defined class. The component, template, and metadata together constitute a view.