Angular 2 & TypeScript Basic Concepts

Posted by Ganesh Patil on August 20, 2016 in Angular-2, Javascript

Once you have setup your first Angular-2 project, what should do next. As angular-2 comes with major changes & enhancements which helps us follow best practices to avoid many compile time errors & run time errors.

Once of such great change is angular-2 now prefers Typescript coding over normal javascript. As typescript is superset of javascript, any javascript code is still valid in typescript. But because of this many developers might find it difficult to migrate from Angular-1 to Angular-2.

This is why before diving into hardcore Angular-2 coding, lets get familier with few things that you will most likely find new in Angular-2 coding style:

IMPORT:

If you have ever used java, c# like any high level language, you must be familiar with the use “import” keyword. It basically used to import class or component¬†from differnt code file so that we can use that class in current file which is importing the other class/component.

Usage:

import ‘MyComponentName’ from ‘./component-dir/my-component-file’

This statement contains two parts first one is name of the component class which file is exporting. And second is path of the file which contains that component defination. This path is relative to current file which is importing other component.

EXPORT:

In typescript, each file is considered as module. And each module often exports one or more things for example Component class or function etc.

Usage:

// filename: myComponent.js

export class MyFirstComponent {

}

Now that we have exported our MyFirstComponent, other modules can use this component using “import” statement.

DECORATORS:

In typescript, a decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

In angular-2 projects you will often find syntax like this “@decoratorName”

COMPONENT:

In Angular-2, components are the main building blocks of the application. This the the place where we define elements of our applicatoin & write logic. In angular 1 we created similar functionality using directives, controllers & scopes, now all these concepts are packed into Components.

 

Usage:

 

import { Component } from '@angular/core';
@Component({
  selector: 'my-first-component',
  template: '<div>{{msg}}</div>'
})
export class MyFirstComponent {
     constructor(){
        this.msg = " HELLO WORLD ";
     }
}

 

Ganesh Patil

Co-Founder of CodeSphere Solutions

Ganesh is passionate about Web Development. He is a minimalist and likes exploring new and interesting technologies. In his free time he likes to play his guitar, watch movies and play with his dog, Penny.

We at CodeSphere Solutions specialize in Web Development. Do you need help with a web development project?

Tell us about it
Share This