Angular 2 Components

 

Components are the main part of the angular 2 application. (a component is a kind of directives)

angular 2 components
angular 2 components
  • Each application is created by putting Components together. (group of components)
  • We should write reusable Components. Write once use many.
  • Nesting Components is what we will see in this tutorial. In our daily work we need to nest component to each other.
  • Components they use data as inputs and outputs.

 

Try it Yourself, live example

try angular 2 components
try angular 2 components

 

  • When have nested components, data should flow thru those components.

 

What’s a Component?
What’s a Component?

 

What’s a Component?

  • A component is a kind of directives.
  • A Component is a piece of code which is able to work in a total autonomy.
  • A Component = Front + Back.
  • A Component is an (ALL-IN-ONE) element = view (frontend) + logic (backend).

 

component vs directive
component vs directive

 

Keep in Mind that: In Angular 2 a Directive can be:

  • A Component.
  • A Structural directive: changes the DOM (e.g. NgIf : show or hide element )
  • An Attribute directive: change the Element (e.g. NgClass : add class to element e.g. span or div … )

 

let's build an example (Data Flow)
let’s build an example (Data Flow)

 

Let’s take an example: our favorite example is a Car.

In a Car we find doors, chairs, a dashboard (speed meter, petrol level, and clock)….

We suppose a Car is the Mothercomponent.

                                 Dashboard is the Child component (Level 1)

 

We can imagine Components in Angular 2 as Multi-level Components communicating with each other.

And of course the communication means Data Exchange.

This mechanism is called: Data Flow.

 

Data Flow
Data Flow

 

  • In this new generation of angular (2) the data binding is unidirectional. Which means a mother pass data to children and then to children etc. this is the default Data Flow.
  • We can pass data from children to parent using Events.
  • This way we can say we have two way data binding
  • you can check [(ngModel)] for a two way data binding. (another tutorial)

 

build mother component

 

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import  {Component} from 'angular2/core';
import {Child} from './child.component';

@Component({
    selector: 'my-app',
    template: `
              <h3 class="titles">Mother Car Component</h3>
              <input type ="text" #textInput value="{{text}}">
              <button (click)="onChange(textInput.value)">Change</button>
              
              <div class="child-style">
                <child [textLevel1]="text" (changed)="onChange($event)">
                </child>
              </div>
    `,
    directives : [Child],
    styles:[`
    
          .titles {
                    color:#0099FF
             }
            .child-style {
                    background-color:#00ffff
            }
            ` ],
})
export class CarComponent {
    text: string;

    onChange(value) {
        this.text = value;
    }

}
/*
 Copyright 2016 angulartypescript.com. All Rights Reserved.
 Everyone can use this source code; don’t forget to indicate the source please:
 http://www.angulartypescript.com/ 
 */

The click button calls a method onChange, this method sets the value of text property.

How to send data from mother to children?

Explanation:

  • Square brackets value [textLevel1] refers to text directive in Child component.
  • We have declared an input (it means that our component Child receives data from the Mother)
  • In Child component the property called textLevel1.
  • we can now write something like (in Mother Component):

<child [textLevel1] =”text” (changed) =”onChange($event)”> </child>

  • Once our data is passed to The Child Component , the Child can now use this it.
build child component
build child component

 

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import  {Component, EventEmitter} from 'angular2/core';
import {Output} from 'angular2/core';

@Component({
    selector: 'child',
    template: `
                <h2>Child Component</h2>
                <input type ="text" #textInput value="{{textLevel1}}">
                <button (click)="onChange(textInput.value)">Change</button>
             `,
    inputs: ['textLevel1'],
    outputs:['changed']
})
export class Child {
    textLevel1: string;
    changed = new EventEmitter();

    onChange(value) {
        this.textLevel1 = value;
        this.changed.emit(value);
    }

}
/*
 Copyright 2016 angulartypescript.com. All Rights Reserved.
 Everyone can use this source code; don’t forget to indicate the source please:
 http://www.angulartypescript.com/ 
 */

How to send data from this Child component to our mother component Car Component?

  • The answer is: @Output () (our Component can emit Data) changed
  • We need to import the EventEmitter from angular2/core

In Child component when we click the button, we fire an event onChange in this action we set the value textLevel1.

And we do the Emit this.changed.emit(value);

When we emit the value from the child, the mother component can then receive the value with this method called changed.

inside parenthesis. (changed)=”onChange($event)”

$event contains the data related to this event.

“If you send a value from children to the mother, the mother sends this data to the children” it’s logic, this is the default Data Flow in Angular 2.

 

Done !