Angular 2 - Part 4 [ Understanding the Component ]

As we have seen angular is composed of lots of modules and component but what really is a component. Well we will learn this in this post

What our normal  app structure looks like - Here I am using the angular-cli

Here we have app.component.ts file inside the app directory which contains following beautiful lines of code:

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'app works!';

  1. The class name for this component is AppComponent
  2. The AppComponent is imported from core angular i.e. @angular/core 
  3. @Component is a decorator which makes this class something special, without this decorator this class will be nothing.
  4. Inside @Component decorator we have
    1. selector : The selector is what allow us to use our component. Its like creating our own html tag which contains certain user define properties. This selectors normally acts like a css selector. 
      1. Lets say we want to use selector as a ID or a class rather then creating this a new tag then we just need to modify selector as
        selector: '.app-root ' for class or
        selector: '#app-root' for id
        So that for eg. whenever we call div with class app-root then the same above component get loaded inside the div and for the ID as well.
    2. templateUrl : yeah! you are right every component must contains the html either inline type or may be load the different html page as shown in the given code. Here we are loading external html page in this component. If we are using the external html page then we need to use templateUrl otherwise we can write html also like

      template : '<div class="myAwesomeClass">{{title}}</div>';
    3. styleUrls: This is same as we decribed in the template section. we can define our own custom css for our componet either using the external css file or inline.
  5. export this keyword enable our component to be exported and use by other component too. 
    1. here title is a property which will be used in our template using the {{}} which is as we can compare with the scope in the angularjs 1
Thats all coders follow next tutorial for more happy coding moments \,,/

1 comment: