By Gary simon - Oct 23, 2016
First, if you prefer watching a video tutorial that explains everything this written tutorial contains, go ahead and watch this video we created:
Simply put, a component in Angular 2 serves as the building blocks of your website or app. You're able to specify both logic and views within components.
A component consists of three sections:
Let's look at a basic component:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
Now, let's examine the above code in detail:
import { Component } from '@angular/core';
"import" allows us to import exported members from the angular library, third party libraries or our owwn modules.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
This is the component decorator. We know it's a decorator because it's preceeded by an "@" symbol. The properties and values inside of it are the metadata. All components must have a selector defined, as well as a template (which can be defined with "templateUrl" or inline html with "template").
The component decorator contains more properties which can be used, depending on the needs of the component.
export class AppComponent {
title = 'app works!';
}
And finally we have the class, which is exported. This means other modules (modules are simply files that import or export other members) can import this component by "import { MyAppComponent } from './path.to.component';"
You can choose to either create a component manually, or use the angular-cli to generate one for you.
If you create a component manually, you have to create the component file "mycomponentname.component.ts". Once you write the code for the component, it must be imported at the top of the app.module.ts file, and the exported class name of the component must be added to the declarations in the app.module.ts file.
If you use the angular-cli to generate a component, it will take care of several areas for you:
To generate a component using the Angular 2 client:
ng generate component componentname
And that's it!