Two of the main parts of any angular 2 application are
- Component
- Module
Module is a container of other application elements such as component,directives.We create a module in angular 2 application using NgModule decorator as we have seen in Developing a Module in Angular 2.
To create component we use the NgComponent decorator.We pass the metadata in the NgComponent decorator function.
Following are the steps to create a component in Angular 2.
- Declare a class.This class represents our component.In the following class we are setting a message property in the constructor.
export class ComponentClass { message:string; constructor(){ this.message="Hello World!"; } }
2. Attach the @Component decorator function to this class.The NgComponent decorator here attaches some data to the class.
This decorator function makes the class an angular component.Without this decorator function ,our class is just like any other class.In the following @Component decorator we are passing to meta data properties selector and template.The selector property is the html tag which we need to use in our html page to call the component.
@Component({ selector: 'my-first-component', template: '<div>Message {{message}}. </button></div>' }) export class ComponentClass { message:string; constructor(){ this.message="Hello World!"; } }
Here we just need to use the <my-first-component></my-first-component> to call our component.
So we need to follow the above two steps to Create Component in Angular 2.
The use of NgComponent is:
- To inform Angular that the class represents a component
- The provided metadata helps Angular generate the appropriate JavaScript for the component class
Leave a Reply