Understand Components in Angular 2


AngularJs 1.0 provide directive controllers, scope to write a components which contains the logic. In AngularJs 1.0 a components can be combination of directives, controllers and scope.

But in Angular 2 Components are way to write elements and logic for application.

For design a component you require at least one @Component and one @View annotation. @Component annotation specifies when a component is instantiated means when we use component in our view then it will initialized the component and called contractor and rendered the view.

When a component is instantiated, Angular

Create DOM for the component.
Load selected template into DOM
Inject objects and render view
Today I am giving one example of components.

 On following example when we use the <first-component></first-component> tag in our View then component will be create, constructor will be called and component rendered.











Plnkr - http://plnkr.co/edit/IAQpVBPhgn1JSokQAux2?p=preview

Component Example in Angular 2

index.html
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<title>Understand Component in Angular 2 </title>
  <script src="https://jspm.io/system@0.18.17.js"></script>
  <script>
    System.config({
      paths: {
        'app.js': 'app.js'
      }
    });
    System.import('app.js');
  </script>
</head>
<body>
  <first-component></first-component>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Understand Component in Angular 2 </title>
  <script src="https://jspm.io/system@0.18.17.js"></script>
  <script src="https://code.angularjs.org/2.0.0-alpha.37/angular2.min.js"></script>

  <script>
    System.config({
      paths: {
        'app.js': 'app.js'
      }
    });
    System.import('app.js');
  </script>
</head>

<body>
  <first-component></first-component>
</body>

</html>
app.es6.js
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//Import Angular
import {Component, View, bootstrap} from 'angular2/angular2';
  
///Define a component
  
// Annotation section
//@Component annotations
@Component({
  selector: 'first-component'
})
//@View annotations
@View({
  template: '<h1>Angular 2   - {{ message }}</h1> '
})
// AngularJs 2 component
class MyComponent {
  name: string;
  constructor() {
    this.message = 'First  Component';
  }
}
bootstrap(MyComponent);
//Import Angular

import {Component, View, bootstrap} from 'angular2/angular2';
 
///Define a component
 
// Annotation section

//@Component annotations
@Component({
  selector: 'first-component'
})

//@View annotations
@View({
  template: '<h1>Angular 2   - {{ message }}</h1> '
})

// AngularJs 2 component
class MyComponent {
  name: string;
  constructor() {
    this.message = 'First  Component';
  }
}

bootstrap(MyComponent);

Keywords - 

Understand Component in Angular 2

How to use Component in Angular 2

Component in Angular 2

Angular 2 component

Comments